<?php

namespace app\admin\controller;

use DateTime;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Queue;
use transfer\Transfer;

class Manage extends Common
{
    /**
     * 列表示例
     * */
    public function listDemo()
    {
        $list = Db::name('menu')->paginate(2);
        $this->assign('list', $list);

        $this->assign('title', '列表示例');
        return $this->fetch();
    }

    /**
     * 列表导出示例
     * */
    public function exportListDemo()
    {
        $title = '文件名';
        $th = ['标题一', '标题二', '标题三'];
        $td = ['key1', 'key2', 'key3'];
        $data = [
            [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ], [
                'key1' => 'value1',
                'key2' => 'value2',
                'key3' => 'value3',
            ]
        ];

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 表单示例
     * */
    public function formDemo()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            echo "<pre>";
            print_r($input);
            exit;
        }
        $this->assign('title', '表单示例');
        return $this->fetch();
    }

    /**
     * 视频分片上传示例
     * */
    public function uploadVideo()
    {
        $this->assign('title', '视频分片上传示例');
        return $this->fetch();
    }

    /**
     * 统计图示例
     * */
    public function chartDemo()
    {
        $this->assign('title', '统计图');
        return $this->fetch();
    }

    /**
     * 树形列表示例
     * */
    public function treeDemo()
    {
        return $this->fetch();
    }

    /**
     * 树状图原始demo
     * */
    public function tree()
    {
        $this->assign('title', 'test');
        return $this->fetch();
    }

    /**
     * iconfont
     * */
    public function iconfont()
    {
        $this->assign('title', 'iconfont');
        return $this->fetch();
    }


    /**
     * 用户列表
     * */
    public function userList()
    {
        $input = Request()->param();

        $username = $input['username'] ? : '';
        $mobile = $input['mobile'] ? : '';
        $pay_name = $input['pay_name'] ? : '';
        $up_company_user_id = $input['company_user_id'] ? : 0;
        $up_channel_user_id = $input['channel_user_id'] ? : 0;
        $up_shop_user_id = $input['shop_user_id'] ? : 0;
        $start_date = $input['start_date'] ? : '';
        $end_date = $input['end_date'] ? : '';

        $login_user_id = session('id');
        $login_user_info = Db::name('user')->where(['id' => $login_user_id])->find();
        $user_type = $login_user_info['user_type'];

        $where['is_admin'] = 0;
        $where['user_type'] = 1;

        if ($username) $where['username'] = ['like', "%$username%"];
        if ($mobile) $where['mobile'] = ['like', "%$mobile%"];
        if ($pay_name) $where['alipay_name|bank_name'] = ['like', "%$pay_name%"];

        if ($user_type == 4) {
            // 门店
            $where['up_shop_user_id'] = $login_user_id;
        } elseif ($user_type == 3) {
            // 渠道/团队长
            $where['up_channel_user_id'] = $login_user_id;
        } elseif ($user_type == 2) {
            // 分公司/运营中心
            $where['up_company_user_id'] = $login_user_id;
        } elseif ($user_type == 5) {
            // 客服
            $where['contact_id'] = $login_user_id;
        }

        if ($up_shop_user_id) {
            $where['up_shop_user_id'] = $up_shop_user_id;
        } elseif ($up_channel_user_id) {
            $where['up_channel_user_id'] = $up_channel_user_id;
        } elseif ($up_company_user_id) {
            $where['up_company_user_id'] = $up_company_user_id;
        }

        if ($start_date || $end_date) {
            $where['create_time'] = ['between', [date('Y-m-d H:i:s', strtotime($start_date)), date('Y-m-d H:i:s', strtotime($end_date . ' 23:59:59'))]];
        }

        $list = Db::name('user')->where($where)->order('id desc')->paginate();
        $this->assign('list', $list);
        $this->assign('title', '用户列表');

        $count = Db::name('user')->where($where)->count();
        $this->assign('count', $count);

        $this->assign('user_type', $user_type);
        if ($login_user_id == 1 || $login_user_info['user_type'] == 0) {
            // 超级管理员
            $company_user_list = Db::name('user')->field('id,username,mobile')->where(['user_type' => 2])->order('id desc')->select();
            if ($company_user_list) {
                foreach ($company_user_list as &$v) {
                    $channel_user_list = Db::name('user')->field('id,username')->where(['user_type' => 3, 'up_company_user_id' => $v['id']])->order('id desc')->select();
                    if ($channel_user_list) {
                        foreach ($channel_user_list as &$val) {
                            $shop_user_list = Db::name('user')->field('id,username')->where(['user_type' => 4, 'up_channel_user_id' => $val['id']])->order('id desc')->select();
                            $val['shop_user_list'] = $shop_user_list ? : [];
                        }
                    }
                    $v['channel_user_list'] = $channel_user_list ? : [];
                }
            }
            $this->assign('company_user_list', $company_user_list);
            $this->assign('company_user_list_json', json_encode($company_user_list, JSON_UNESCAPED_UNICODE));
        } elseif ($login_user_info['user_type'] == 2) {
            // 分公司/运营中心
            $channel_user_list = Db::name('user')->field('id,username')->where(['user_type' => 3, 'up_company_user_id' => $login_user_id])->order('id desc')->select();
            if ($channel_user_list) {
                foreach ($channel_user_list as &$v) {
                    $shop_user_list = Db::name('user')->field('id,username')->where(['user_type' => 4, 'up_channel_user_id' => $v['id']])->order('id desc')->select();
                    $v['shop_user_list'] = $shop_user_list ? : [];
                }
            }
            $this->assign('channel_user_list', $channel_user_list);
            $this->assign('channel_user_list_json', json_encode($channel_user_list, JSON_UNESCAPED_UNICODE));
        } elseif ($login_user_info['user_type'] == 3) {
            // 渠道/团队长
            $shop_user_list = Db::name('user')->field('id,username')->where(['user_type' => 4, 'up_channel_user_id' => $login_user_id])->order('id desc')->select();
            $this->assign('shop_user_list', $shop_user_list);
        }

        return $this->view->fetch();
    }

    /**
     * 门店二维码
     * */
    public function shopQr()
    {
        $login_user_id = session('id');
        $info = Db::name('user')->where(['id' => $login_user_id])->find();
        $shop_qr = $info['shop_qr'];
        if (!$shop_qr && $info['user_type'] == 4) {
            $shop_qr = createShopQr($login_user_id);
        }
        $this->assign('shop_qr', $shop_qr);

        $this->assign('user_type', $info['user_type']);

        $this->assign('title', '门店二维码');
        return $this->fetch();
    }

    /**
     * 将用户的打卡状态设置为正常
     * */
    public function setClockStatus()
    {
        $id = Request()->param('id');
        $clock_status = Request()->param('clock_status');

        if (empty($id)) adminReturn(2, '参数错误');
        if ($clock_status != 0 && $clock_status != 3) adminReturn(2, '参数错误');

        if ($clock_status == 3) {
            $count = Db::name('user_clock')->where(['user_id' => $id])->count();
            if ($count == 0) {
                // 还未生成打卡记录
                $clock_status = 1;
            } elseif ($count > 0) {
                // 已经打过卡了
                $clock_status = 2;
            }
        }

        $res = Db::name('user')->where(['id' => $id])->update(['clock_status' => $clock_status, 'update_time' => time()]);
        if ($res) {
            adminReturn(1, '设置成功');
        } else {
            adminReturn(2, '设置失败');
        }
    }

    /**
     * 新增/编辑 用户
     * */
    public function doUser()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $username = $input['username'];
            $is_vip = $input['is_vip'];
            $is_repurchase = $input['is_repurchase'];
            $repurchase_desc = $input['repurchase_desc'] ? : '';
            $account_type = $input['account_type'] ? : '';
            $alipay_name = $input['alipay_name'] ? : '';
            $alipay_mobile = $input['alipay_mobile'] ? : '';
            $bank_name = $input['bank_name'] ? : '';
            $bank_num = $input['bank_num'] ? : '';
            $bank_user = $input['bank_user'] ? : '';
            $clock_status = $input['clock_status'] ? : '';

            if (empty($username)) adminReturn(2, '请输入昵称');

            $data = [
                'is_vip' => $is_vip,
                'username' => $username,
                'is_repurchase' => $is_repurchase,
                'repurchase_desc' => $repurchase_desc,
                'account_type' => $account_type,
                'alipay_name' => $alipay_name,
                'alipay_mobile' => $alipay_mobile,
                'bank_name' => $bank_name,
                'bank_num' => $bank_num,
                'bank_user' => $bank_user,
                'clock_status' => $clock_status,
            ];

            $time = time();
            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('user')->where(['id' => $id])->update($data);
                if ($res) {
                    //                    adminReturn(1, '编辑成功', url('userList'));
                    adminReturn(1, '编辑成功', 'userList', ['reloadUrl' => true]);
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('userList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('user')->where(['id' => $id])->find();
            }

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '用户');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 分公司/运营中心 列表
     * */
    public function companyList()
    {

        $where['user_type'] = 2;
        $where['status'] = 1;

        $login_user_id = session('id');
        $login_user_info = Db::name('user')->where(['id' => $login_user_id])->find();
        $load_list = true;
        if ($login_user_info['user_type'] == 5) {
            // 客服
            $company_ids = Db::name('shop_contact')->where(['contact_id' => $login_user_id])->column('company_id');
            if ($company_ids) {
                $where['id'] = ['in', $company_ids];
            } else {
                $load_list = false;
            }
        }

        if ($load_list) {
            $list = Db::name('user')->where($where)->order('id desc')->paginate();
        }
        $this->assign('list', $list ? : []);

        $this->assign('title', '分公司/运营中心 列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 分公司/运营中心
     * */
    public function doCompany()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'] ? : 0;
            $username = $input['username'];
            $account = $input['account'];
            $password = $input['password'];
            $re_password = $input['re_password'];
            $ident_name = $input['ident_name'];

            if (empty($username)) adminReturn(2, '请输入名称');
            if (empty($account)) adminReturn(2, '请输入账号');
            if ($id == 0) {
                if (empty($password)) adminReturn(2, '请输入密码');
                if (empty($re_password)) adminReturn(2, '请输入确认密码');
                if (strlen($password) < 6) apiReturn(2, '密码长度至少6位');
                if ($password !== $re_password) adminReturn(2, '两次密码不一致，请重新输入');
            }

            if ($id) $where['id'] = ['neq', $id];
            $where['account'] = $account;
            $where['is_admin'] = 1;

            $count = Db::name('user')->where($where)->count();
            if ($count) adminReturn(2, '账号已存在');

            Db::startTrans();
            try {
                if ($id) {
                    $data = [
                        'account' => $account,
                        'username' => $username,
                        'ident_name' => $ident_name,
                        'update_time' => time()
                    ];

                    $res = Db::name('user')->where(['id' => $id])->update($data);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '编辑失败');
                    }
                } else {
                    $data = [
                        'account' => $account,
                        'username' => $username,
                        'password' => thinkEncrypt($password),
                        'ident_name' => $ident_name,
                        'status' => 1,
                        'is_admin' => 1,
                        'user_type' => 2,
                        'create_time' => time()
                    ];
                    $user_id = Db::name('user')->insertGetId($data);

                    if (!$user_id) {
                        Db::rollback();
                        adminReturn(2, '新增失败');
                    }

                    $auth_data = [
                        'uid' => $user_id,
                        'group_id' => 1
                    ];
                    $res = Db::name('auth_group_access')->insert($auth_data);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '新增失败');
                    }
                }

                Db::commit();
                adminReturn(1, '操作成功', url('companyList'), $id > 0 ? ['reloadUrl' => true] : []);
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('user')->where(['id' => $id])->find();

            $this->assign('info', $info);

            $this->assign('title', ($id ? '编辑' : '新增') . '分公司/运营中心');
            return $this->view->fetch();
        }
    }

    /**
     * 删除分公司/运营中心
     * */
    public function delCompany()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('user')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                $res = Db::name('user')->where(['id' => $id])->delete();
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '删除失败');
                }

                $res = Db::name('auth_group_access')->where(['uid' => $id])->delete();
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '删除失败');
                }

                Db::commit();
                adminReturn(1, '删除成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 渠道/团队长 列表
     * */
    public function channelList()
    {
        $where['user_type'] = 3;
        $where['status'] = 1;

        $login_user_id = session('id');
        $login_user_info = Db::name('user')->where(['id' => $login_user_id])->find();
        $this->assign('user_type', $login_user_info['user_type']);
        if ($login_user_id == 1 || $login_user_info['user_type'] == 0) {
            // 超级管理员 || 后台【权限干礼】新建权限用户
            $up_company_user_id = $this->request->param('up_company_user_id', 0);
            if ($up_company_user_id) $where['up_company_user_id'] = $up_company_user_id;
        } else {
            $where['up_company_user_id'] = $login_user_id;
        }

        $load_list = true;
        if ($login_user_info['user_type'] == 5) {
            // 客服
            $channel_ids = Db::name('shop_contact')->where(['contact_id' => $login_user_id])->column('channel_id');
            if ($channel_ids) {
                $where['id'] = ['in', $channel_ids];
            } else {
                $load_list = false;
            }
        }

        if ($load_list) {
            $list = Db::name('user')->where($where)->order('id desc')->paginate();
        }
        $this->assign('list', $list ? : []);

        // 分公司列表
        $company_list = Db::name('user')->where(['user_type' => 2])->order('id desc')->select();
        $this->assign('company_list', $company_list);

        $this->assign('title', '渠道/团队长 列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 渠道/团队长
     * */
    public function doChannel()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'] ? : 0;
            $username = $input['username'];
            $account = $input['account'];
            $password = $input['password'];
            $re_password = $input['re_password'];
            $ident_name = $input['ident_name'];
            $up_company_user_id = $input['up_company_user_id'] ? : 0;

            if (empty($username)) adminReturn(2, '请输入名称');
            if (empty($account)) adminReturn(2, '请输入账号');
            if ($id == 0) {
                if (empty($password)) adminReturn(2, '请输入密码');
                if (empty($re_password)) adminReturn(2, '请输入确认密码');
                if (strlen($password) < 6) apiReturn(2, '密码长度至少6位');
                if ($password !== $re_password) adminReturn(2, '两次密码不一致，请重新输入');
            }

            $login_user_id = session('id');
            $login_user_info = Db::name('user')->where(['id' => $login_user_id])->find();
            if ($login_user_id == 1 || $login_user_info['user_type'] == 0) {
                // 超级管理员
                if (empty($up_company_user_id)) adminReturn(2, '请选择分公司/运营中心');
            } else {
                $up_company_user_id = $login_user_id;
            }

            if ($id) $where['id'] = ['neq', $id];
            $where['account'] = $account;
            $where['is_admin'] = 1;

            $count = Db::name('user')->where($where)->count();
            if ($count) adminReturn(2, '账号已存在');

            Db::startTrans();
            try {
                if ($id) {
                    $data = [
                        'username' => $username,
                        'account' => $account,
                        'ident_name' => $ident_name,
                        'up_company_user_id' => $up_company_user_id,
                        'update_time' => time()
                    ];

                    $res = Db::name('user')->where(['id' => $id])->update($data);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '编辑失败');
                    }
                } else {
                    $data = [
                        'account' => $account,
                        'username' => $username,
                        'password' => thinkEncrypt($password),
                        'ident_name' => $ident_name,
                        'up_company_user_id' => $up_company_user_id,
                        'status' => 1,
                        'is_admin' => 1,
                        'user_type' => 3,
                        'create_time' => time()
                    ];
                    $user_id = Db::name('user')->insertGetId($data);

                    if (!$user_id) {
                        Db::rollback();
                        adminReturn(2, '新增失败');
                    }

                    $auth_data = [
                        'uid' => $user_id,
                        'group_id' => 2
                    ];
                    $res = Db::name('auth_group_access')->insert($auth_data);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '新增失败');
                    }
                }

                Db::commit();
                adminReturn(1, '操作成功', url('channelList'), $id > 0 ? ['reloadUrl' => true] : []);
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('user')->where(['id' => $id])->find();

            $this->assign('info', $info);

            $this->assign('title', ($id ? '编辑' : '新增') . '渠道/团队长');

            // 分公司列表
            $company_list = Db::name('user')->where(['user_type' => 2])->order('id desc')->select();
            $this->assign('company_list', $company_list);

            // 查询当前登录人的user_type
            $login_user_id = session('id');
            $user_type = Db::name('user')->where(['id' => $login_user_id])->value('user_type');
            $this->assign('user_type', $user_type);

            return $this->view->fetch();
        }
    }

    /**
     * 删除分公司/运营中心
     * */
    public function delChannel()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('user')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                $res = Db::name('user')->where(['id' => $id])->delete();
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '删除失败');
                }

                $res = Db::name('auth_group_access')->where(['uid' => $id])->delete();
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '删除失败');
                }

                Db::commit();
                adminReturn(1, '删除成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 门店列表
     * */
    public function shopList()
    {
        $where['user_type'] = 4;
        $where['status'] = 1;

        $login_user_id = session('id');
        $login_user_info = Db::name('user')->where(['id' => $login_user_id])->find();
        $this->assign('user_type', $login_user_info['user_type']);
        if ($login_user_id == 1 || $login_user_info['user_type'] == 0) {
            $up_company_user_id = $this->request->param('up_company_user_id', 0);
            $up_channel_user_id = $this->request->param('up_channel_user_id', 0);
            if ($up_company_user_id) $where['up_company_user_id'] = $up_company_user_id;
            if ($up_channel_user_id) $where['up_channel_user_id'] = $up_channel_user_id;
        } else {

            if ($login_user_info['user_type'] == 2) {
                // 分公司
                $where['up_company_user_id'] = $login_user_id;
            } elseif ($login_user_info['user_type'] == 3) {
                // 渠道/团队长
                $where['up_channel_user_id'] = $login_user_id;
            }
        }

        $load_list = true;
        if ($login_user_info['user_type'] == 5) {
            // 客服
            $shop_ids = Db::name('shop_contact')->where(['contact_id' => $login_user_id])->column('shop_id');
            if ($shop_ids) {
                $where['id'] = ['in', $shop_ids];
            } else {
                $load_list = false;
            }
        }

        if ($load_list) {
            $list = Db::name('user')->where($where)->order('id desc')->paginate();
        }
        $this->assign('list', $list ? : []);

        if ($login_user_id == 1 || $login_user_info['user_type'] == 0) {
            $company_list = Db::name('user')->where(['user_type' => 2])->order('id desc')->select();
            if ($company_list) {
                foreach ($company_list as &$v) {
                    $channel_list = Db::name('user')->where(['user_type' => 3, 'up_company_user_id' => $v['id']])->select();
                    $v['channel_list'] = $channel_list ? : [];
                }
            }
            $this->assign('company_list', $company_list);
            $this->assign('company_list_json', json_encode($company_list, JSON_UNESCAPED_UNICODE));
        } else {
            $channel_list = Db::name('user')->where(['user_type' => 3, 'up_company_user_id' => $login_user_id])->order('id desc')->select();
            $this->assign('channel_list', $channel_list);
        }

        $this->assign('user_type', $login_user_info['user_type']);
        $this->assign('title', '门店列表');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑门店
     * */
    public function doShop()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'] ? : 0;
            $username = $input['username'];
            $account = $input['account'];
            $password = $input['password'];
            $re_password = $input['re_password'];
            $up_channel_user_id = $input['up_channel_user_id'] ? : 0;

            if (empty($username)) adminReturn(2, '请输入名称');
            if (empty($account)) adminReturn(2, '请输入账号');
            if ($id == 0) {
                if (empty($password)) adminReturn(2, '请输入密码');
                if (empty($re_password)) adminReturn(2, '请输入确认密码');
                if (strlen($password) < 6) apiReturn(2, '密码长度至少6位');
                if ($password !== $re_password) adminReturn(2, '两次密码不一致，请重新输入');
            }

            $login_user_id = session('id');
            $login_user_info = Db::name('user')->where(['id' => $login_user_id])->find();
            if ($login_user_id == 1 || $login_user_info['user_type'] == 0) {
                // 超级管理员
                if (empty($up_channel_user_id)) adminReturn(2, '请选择渠道/团队长');

                $up_company_user_id = $input['up_company_user_id'];
            } elseif ($login_user_info['user_type'] == 2) {
                // 分公司/运营中心
                $up_company_user_id = $login_user_id;
            } elseif ($login_user_info['user_type'] == 3) {
                // 渠道/团队长
                $up_channel_user_id = $login_user_id;
                $up_company_user_id = Db::name('user')->where(['id' => $up_channel_user_id])->value('up_company_user_id');
            }


            if ($id) $where['id'] = ['neq', $id];
            $where['account'] = $account;
            $where['is_admin'] = 1;

            $count = Db::name('user')->where($where)->count();
            if ($count) adminReturn(2, '账号已存在');

            Db::startTrans();
            try {
                if ($id) {
                    $data = [
                        'username' => $username,
                        'account' => $account,
                        'password' => thinkEncrypt($password),
                        'up_company_user_id' => $up_company_user_id,
                        'up_channel_user_id' => $up_channel_user_id,
                        'update_time' => time()
                    ];

                    $res = Db::name('user')->where(['id' => $id])->update($data);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '编辑失败');
                    }
                } else {
                    $data = [
                        'account' => $account,
                        'username' => $username,
                        'password' => thinkEncrypt($password),
                        'up_company_user_id' => $up_company_user_id,
                        'up_channel_user_id' => $up_channel_user_id,
                        'status' => 1,
                        'is_admin' => 1,
                        'user_type' => 4,
                        'create_time' => time()
                    ];
                    $user_id = Db::name('user')->insertGetId($data);

                    if (!$user_id) {
                        Db::rollback();
                        adminReturn(2, '新增失败');
                    }

                    $auth_data = [
                        'uid' => $user_id,
                        'group_id' => 3
                    ];
                    $res = Db::name('auth_group_access')->insert($auth_data);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '新增失败');
                    }
                }

                createShopQr($user_id ? : $id);
                Db::commit();
                adminReturn(1, '操作成功', url('shopList'), $id > 0 ? ['reloadUrl' => true] : []);
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('user')->where(['id' => $id])->find();

            $this->assign('info', $info);

            $this->assign('title', ($id ? '编辑' : '新增') . '门店');

            $login_user_id = session('id');
            $login_user_info = Db::name('user')->where(['id' => $login_user_id])->find();
            if ($login_user_id == 1 || $login_user_info['user_type'] == 0) {
                $company_list = Db::name('user')->field('id,username')->where(['user_type' => 2])->order('id desc')->select();
                if ($company_list) {
                    foreach ($company_list as &$v) {
                        $channel_list = Db::name('user')->field('id,username')->where(['up_company_user_id' => $v['id'], 'user_type' => 3])->select();
                        $v['channel_list'] = $channel_list ? : [];
                    }
                }
                $this->assign('company_list', $company_list ? : []);
                $this->assign('company_list_json', json_encode($company_list, JSON_UNESCAPED_UNICODE));
            } else {
                if ($login_user_info['user_type'] == 2) {
                    // 分公司/运营中心
                    $channel_list = Db::name('user')->field('id,username')->where(['up_company_user_id' => $login_user_id, 'user_type' => 3])->select();
                    $this->assign('channel_list', $channel_list);
                }
            }

            $this->assign('user_type', $login_user_info['user_type']);
            return $this->view->fetch();
        }
    }

    /**
     * 删除门店
     * */
    public function delShop()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('user')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                $res = Db::name('user')->where(['id' => $id])->delete();
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '删除失败');
                }

                $res = Db::name('auth_group_access')->where(['uid' => $id])->delete();
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '删除失败');
                }

                Db::commit();
                adminReturn(1, '删除成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 一键更新推广码
     * */
    public function updateAllShopQr()
    {
        $list = Db::name('user')->where(['user_type' => 4])->column('id');
        if ($list) {
            foreach ($list as $v) {
                createShopQr($v);
            }
        }
        adminReturn(1, '操作成功');
    }

    /**
     * 重置密码
     * */
    public function initPwd()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('user')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('user')->where(['id' => $id])->update(['password' => thinkEncrypt('123456'), 'update_time' => time()]);
            if ($res) {
                adminReturn(1, '重置成功');
            } else {
                adminReturn(2, '重置失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 客服列表
     * */
    public function contactList()
    {
        $where['u.user_type'] = 5;

        $login_user_id = session('id');
        $login_user_info = Db::name('user')->where(['id' => $login_user_id])->find();
        $this->assign('user_type', $login_user_info['user_type']);

        if ($login_user_id == 1 || $login_user_info['user_type'] == 0) {
            $up_company_user_id = $this->request->param('up_company_user_id', 0);
            $up_channel_user_id = $this->request->param('up_channel_user_id', 0);
            $up_shop_user_id = $this->request->param('up_shop_user_id', 0);
            if ($up_company_user_id) $where['s.company_id'] = $up_company_user_id;
            if ($up_channel_user_id) $where['s.channel_id'] = $up_channel_user_id;
            if ($up_shop_user_id) $where['s.shop_id'] = $up_shop_user_id;
        } else {
            if ($login_user_info['user_type'] == 2) {
                // 分公司
                $where['s.company_id'] = $login_user_id;
            } elseif ($login_user_info['user_type'] == 3) {
                // 渠道/团队长
                $where['s.channel_id'] = $login_user_id;
            } elseif ($login_user_info['user_type'] == 4) {
                // 门店
                $where['s.shop_id'] = $login_user_id;
            }
        }

        $list = Db::name('user u')
            ->join('ck_shop_contact s', 'u.id = s.contact_id', 'left')
            ->field('u.*')
            ->where($where)
            ->group('u.id')
            ->order('u.id desc')
            ->paginate()
            ->each(function ($v) {
                $company_ids = Db::name('shop_contact')->where(['contact_id' => $v['id']])->column('company_id');
                $v['company_ids'] = $company_ids ? : [];

                $channel_ids = Db::name('shop_contact')->where(['contact_id' => $v['id']])->column('channel_id');
                $v['channel_ids'] = $channel_ids ? : [];

                $shop_ids = Db::name('shop_contact')->where(['contact_id' => $v['id']])->column('shop_id');
                $v['shop_ids'] = $shop_ids ? : [];

                return $v;
            });


        $this->assign('list', $list);

        if ($login_user_id == 1 || $login_user_info['user_type'] == 0) {
            $company_list = Db::name('user')->where(['user_type' => 2])->order('id desc')->select();
            if ($company_list) {
                foreach ($company_list as &$v) {
                    $channel_list = Db::name('user')->where(['user_type' => 3, 'up_company_user_id' => $v['id']])->select();
                    if ($channel_list) {
                        foreach ($channel_list as &$val) {
                            $shop_list = Db::name('user')->where(['user_type' => 4, 'up_channel_user_id' => $val['id']])->select();
                            $val['shop_list'] = $shop_list ? : [];
                        }
                    }
                    $v['channel_list'] = $channel_list ? : [];
                }
            }
            $this->assign('company_list', $company_list);
            $this->assign('company_list_json', json_encode($company_list, JSON_UNESCAPED_UNICODE));
        } elseif ($login_user_info['user_type'] == 2) {
            $channel_list = Db::name('user')->where(['user_type' => 3, 'up_company_user_id' => $login_user_id])->order('id desc')->select();
            if ($channel_list) {
                foreach ($channel_list as &$val) {
                    $shop_list = Db::name('user')->where(['user_type' => 4, 'up_channel_user_id' => $val['id']])->select();
                    $val['shop_list'] = $shop_list ? : [];
                }
            }
            $this->assign('channel_list', $channel_list);
        } elseif ($login_user_info['user_type'] == 3) {
            $shop_list = Db::name('user')->where(['user_type' => 4, 'up_channel_user_id' => $login_user_id])->order('id desc')->select();
            $this->assign('shop_list', $shop_list);
        }

        $this->assign('title', '客服列表');
        return $this->view->fetch();
    }


    /**
     * 新增/编辑 客服
     * */
    public function doContact()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'] ? : 0;
            $username = $input['username'];
            $account = $input['account'];
            $password = $input['password'];
            $re_password = $input['re_password'];
            $shop_ids = $input['shop_ids'] ? : 0;

            if (empty($username)) adminReturn(2, '请输入名称');
            if (empty($account)) adminReturn(2, '请输入账号');
            if ($id == 0) {
                if (empty($password)) adminReturn(2, '请输入密码');
                if (empty($re_password)) adminReturn(2, '请输入确认密码');
                if (strlen($password) < 6) apiReturn(2, '密码长度至少6位');
                if ($password !== $re_password) adminReturn(2, '两次密码不一致，请重新输入');
            }

            $login_user_id = session('id');
            $login_user_info = Db::name('user')->where(['id' => $login_user_id])->find();
            if ($login_user_info['user_type'] == 4) {
                // 门店账号
                $shop_ids = [$login_user_id];
            } else {
                // 非门店账号
                if (empty($shop_ids)) apiReturn(2, '请选择门店');
            }


            if ($id) $where['id'] = ['neq', $id];
            $where['account'] = $account;
            $where['is_admin'] = 1;

            $count = Db::name('user')->where($where)->count();
            if ($count) adminReturn(2, '账号已存在');

            Db::startTrans();
            try {
                if ($id) {
                    $data = [
                        'username' => $username,
                        'account' => $account,
                        'update_time' => time()
                    ];
                    if ($password) $data['password'] = thinkEncrypt($password);

                    $res = Db::name('user')->where(['id' => $id])->update($data);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '编辑失败');
                    }

                    $res = Db::name('shop_contact')->where(['contact_id' => $id])->delete();
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '编辑失败');
                    }
                } else {
                    $data = [
                        'account' => $account,
                        'username' => $username,
                        'password' => thinkEncrypt($password),
                        'status' => 1,
                        'is_admin' => 1,
                        'user_type' => 5,
                        'create_time' => time()
                    ];
                    $user_id = Db::name('user')->insertGetId($data);

                    if (!$user_id) {
                        Db::rollback();
                        adminReturn(2, '新增失败');
                    }


                    $auth_data = [
                        'uid' => $user_id,
                        'group_id' => 4
                    ];
                    $res = Db::name('auth_group_access')->insert($auth_data);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '新增失败');
                    }
                }


                $shop_contact_data = [];
                foreach ($shop_ids as $v) {
                    $info = Db::name('user')->where(['id' => $v])->find();
                    if (empty($info)) continue;

                    $shop_contact_data[] = [
                        'company_id' => $info['up_company_user_id'],
                        'channel_id' => $info['up_channel_user_id'],
                        'shop_id' => $v,
                        'contact_id' => $user_id ? : $id,
                        'update_time' => time()
                    ];
                }
                if ($shop_contact_data) {
                    $res = Db::name('shop_contact')->insertAll($shop_contact_data);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '新增失败');
                    }
                }

                Db::commit();
                adminReturn(1, '操作成功', url('contactList'), $id > 0 ? ['reloadUrl' => true] : []);
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('user')->where(['id' => $id])->find();

            $this->assign('info', $info);

            $this->assign('title', ($id ? '编辑' : '新增') . '客服');

            $login_user_id = session('id');
            $login_user_info = Db::name('user')->where(['id' => $login_user_id])->find();
            if ($login_user_info['user_type'] == 0) {
                // 管理员
                $company_list = Db::name('user')->field('id,username name')->where(['user_type' => 2])->select();
                if ($company_list) {
                    foreach ($company_list as &$v) {
                        $channel_list = Db::name('user')->field('id,username name')->where(['user_type' => 3, 'up_company_user_id' => $v['id']])->select();
                        if ($channel_list) {
                            foreach ($channel_list as &$val) {
                                $shop_list = Db::name('user')->field('id,username name')->where(['user_type' => 4, 'up_channel_user_id' => $val['id']])->select();
                                $val['three_list'] = $shop_list ? : [];
                            }
                        }
                        $v['two_list'] = $channel_list ? : [];
                    }
                }
                $this->assign('one_list', $company_list ? : []);
            } elseif ($login_user_info['user_type'] == 2) {
                // 分公司/运营中心
                $channel_list = Db::name('user')->field('id,username name')->where(['user_type' => 3, 'up_company_user_id' => $login_user_id])->select();
                if ($channel_list) {
                    foreach ($channel_list as &$val) {
                        $shop_list = Db::name('user')->field('id,username name')->where(['user_type' => 4, 'up_channel_user_id' => $val['id']])->select();
                        $val['two_list'] = $shop_list ? : [];
                    }
                }
                $this->assign('one_list', $channel_list ? : []);
            } elseif ($login_user_info['user_type'] == 3) {
                // 渠道/团队长
                $shop_list = Db::name('user')->field('id,username name')->where(['user_type' => 4, 'up_channel_user_id' => $login_user_id])->select();
                $this->assign('one_list', $shop_list ? : []);
            }

            $check_shop_ids = Db::name('shop_contact')->where(['contact_id' => $id])->column('shop_id');
            $this->assign('check_shop_ids', json_encode($check_shop_ids, JSON_UNESCAPED_UNICODE));

            $this->assign('user_type', $login_user_info['user_type']);
            return $this->view->fetch();
        }
    }

    /**
     * 分配客户
     * */
    public function allocateUserToContact()
    {
        $input = Request()->param();

        $id = $input['id'];// 客服id
        $user_ids = $input['user_ids'] ? : [];

        if (empty($id)) adminReturn(2, '客服ID缺失');
        //        if (empty($user_ids)) adminReturn(2, '请选择客户');


        Db::startTrans();
        try {
            $count = Db::name('user')->where('contact_id', $id)->count();
            if ($count) {
                $res = Db::name('user')->where('contact_id', $id)->update(['contact_id' => 0, 'update_time' => time()]);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }
            }

            if ($user_ids) {
                $res = Db::name('user')->whereIn('id', $user_ids)->update(['contact_id' => $id, 'update_time' => time()]);
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '操作失败');
                }
            }

            Db::commit();
            adminReturn(1, '操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 启用/禁用
     * */
    public function doContactStatus()
    {
        $id = Request()->param('id');
        $status = Request()->param('status');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('user')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('user')->where(['id' => $id])->setField('status', $status);
            if ($res) {
                adminReturn(1, '操作成功');
            } else {
                adminReturn(2, '操作失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 删除客服
     * */
    public function delContact()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('user')->where(['id' => $id])->find();
        if ($info) {
            Db::startTrans();
            try {
                $res = Db::name('user')->where(['id' => $id])->delete();
                if (!$res) {
                    Db::rollback();
                    adminReturn(2, '删除失败');
                }

                $count = Db::name('user')->where(['contact_id' => $id])->count();
                if ($count > 0) {
                    $res = Db::name('user')->where(['contact_id' => $id])->update(['contact_id' => 0, 'update_time' => time()]);
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '删除失败');
                    }
                }

                $count = Db::name('shop_contact')->where(['contact_id' => $id])->count();
                if ($count) {
                    $res = Db::name('shop_contact')->where(['contact_id' => $id])->delete();
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '删除失败');
                    }
                }

                $count = Db::name('auth_group_access')->where(['uid' => $id])->count();
                if ($count) {
                    $res = Db::name('auth_group_access')->where(['uid' => $id])->delete();
                    if (!$res) {
                        Db::rollback();
                        adminReturn(2, '删除失败');
                    }
                }

                Db::commit();
                adminReturn(1, '删除成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '删除失败' . $e->getMessage());
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 用户打卡明细
     * */
    public function userClockList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'] ? : 0;

        if (empty($user_id)) adminReturn(2, '参数缺失');

        $list = Db::name('user_clock')->where(['user_id' => $user_id])->order('day asc, id asc')->paginate(18)->each(function ($v) {
            $imgs_json = json_decode($v['imgs_json'], true);
            $v['imgs_text_json'] = implode('%,%', json_decode($v['imgs_text_json'], true));
            $imgs = [];
            foreach ($imgs_json as $key => $val) {
                $imgs[$key]['path'] = $val;
            }
            $v['imgs'] = $imgs;

            $v['video'] = json_decode($v['video_json'], true);

            switch ($v['status']) {
                case 0:
                    $v['status_text'] = '未打卡';
                    break;
                case 1:
                    $v['status_text'] = '初审通过';
                    break;
                case 2:
                    $v['status_text'] = '复审通过';
                    break;
                case -1:
                    $v['status_text'] = '已驳回';
                    break;
            }

            $pay_desc = '';
            if ($v['pay_status'] == 0) {
                $pay_desc = $v['is_pay'] ? '已打款' : '未打款';
            } else {
                switch ($v['pay_status']) {
                    case 1:
                        $pay_desc = '待用户收款';
                        break;
                    case 2:
                        $pay_desc = '已打款';
                        break;
                    case 3:
                        $pay_desc = '未打款';
                        break;
                }
            }
            $v['pay_desc'] = $pay_desc;

            return $v;
        });
        $this->assign('list', $list);

        $this->assign('title', '打卡明细');
        return $this->view->fetch();
    }

    /**
     * 打卡记录列表
     * */
    public function clockList()
    {
        $input = Request()->param();

        $start_date = $input['start_date'] ? : '';
        $end_date = $input['end_date'] ? : '';
        $status = $input['status'];
        $up_company_user_id = $input['company_user_id'] ? : 0;
        $up_channel_user_id = $input['channel_user_id'] ? : 0;
        $up_shop_user_id = $input['shop_user_id'] ? : 0;

        $login_user_id = session('id');
        $login_user_info = Db::name('user')->where(['id' => $login_user_id])->find();
        $user_type = $login_user_info['user_type'];

        $where_field = '';
        $user_id = $login_user_id;
        if ($user_type == 4) {
            // 门店
            $where_field = 'u.up_shop_user_id';
        } elseif ($user_type == 3) {
            // 渠道/团队长
            $where_field = 'u.up_channel_user_id';
        } elseif ($user_type == 2) {
            // 分公司/运营中心
            $where_field = 'u.up_company_user_id';
        }

        if ($up_shop_user_id) {
            $where_field = 'u.up_shop_user_id';
            $user_id = $up_shop_user_id;
        } elseif ($up_channel_user_id) {
            $where_field = 'u.up_channel_user_id';
            $user_id = $up_channel_user_id;
        } elseif ($up_company_user_id) {
            $where_field = 'u.up_company_user_id';
            $user_id = $up_company_user_id;
        }

        if ($start_date || $end_date) {
            $where['uc.ck_date'] = ['between', [$start_date, $end_date]];
        } else {
            $where['uc.ck_date'] = date('Y-m-d');
        }

        if ($status != 0) {
            if ($status > 0) {
                $where['uc.status'] = $status - 1;
            } else {
                $where['uc.status'] = $status;
            }
        }
        if ($where_field) $where[$where_field] = $user_id;

        $load_list = true;
        if ($user_type == 5) {
            // 客服
            $user_ids = Db::name('user')->where(['contact_id' => $login_user_id])->column('id');
            if ($user_ids) {
                $where['u.id'] = ['in', $user_ids];
            } else {
                $load_list = false;
            }
        }

        if ($load_list) {
            $list = Db::name('user_clock uc')->join('ck_user u', 'uc.user_id = u.id')
                ->field('uc.*,u.username')
                ->where($where)
                ->order('day asc,id asc')
                ->paginate(18)
                ->each(function ($v) {
                    $imgs_json = json_decode($v['imgs_json'], true);
                    $v['imgs_text_json'] = implode('%,%', json_decode($v['imgs_text_json'], true));
                    $imgs = [];
                    foreach ($imgs_json as $key => $val) {
                        $imgs[$key]['path'] = $val;
                    }
                    $v['imgs'] = $imgs;

                    $v['video'] = json_decode($v['video_json'], true);

                    switch ($v['status']) {
                        case 0:
                            $v['status_text'] = '未打卡';
                            break;
                        case 1:
                            $v['status_text'] = '初审通过';
                            break;
                        case 2:
                            $v['status_text'] = '复审通过';
                            break;
                        case -1:
                            $v['status_text'] = '已驳回';
                            break;
                    }

                    $pay_desc = '';
                    if ($v['pay_status'] == 0) {
                        $pay_desc = $v['is_pay'] ? '已打款' : '未打款';
                    } else {
                        switch ($v['pay_status']) {
                            case 1:
                                $pay_desc = '待用户收款';
                                break;
                            case 2:
                                $pay_desc = '已打款';
                                break;
                            case 3:
                                $pay_desc = '未打款';
                                break;
                        }
                    }
                    $v['pay_desc'] = $pay_desc;

                    return $v;
                });

            $count = Db::name('user_clock uc')->join('ck_user u', 'uc.user_id = u.id')->where($where)->count();
        } else {
            $list = [];
            $count = 0;
        }

        $this->assign('count', $count);
        $this->assign('list', $list);

        $this->assign('title', '打卡记录列表');

        $this->assign('user_type', $user_type);
        if ($login_user_id == 1 || $login_user_info['user_type'] == 0) {
            // 超级管理员
            $company_user_list = Db::name('user')->field('id,username,mobile')->where(['user_type' => 2])->order('id desc')->select();
            if ($company_user_list) {
                foreach ($company_user_list as &$v) {
                    $channel_user_list = Db::name('user')->field('id,username')->where(['user_type' => 3, 'up_company_user_id' => $v['id']])->order('id desc')->select();
                    if ($channel_user_list) {
                        foreach ($channel_user_list as &$val) {
                            $shop_user_list = Db::name('user')->field('id,username')->where(['user_type' => 4, 'up_channel_user_id' => $val['id']])->order('id desc')->select();
                            $val['shop_user_list'] = $shop_user_list ? : [];
                        }
                    }
                    $v['channel_user_list'] = $channel_user_list ? : [];
                }
            }
            $this->assign('company_user_list', $company_user_list);
            $this->assign('company_user_list_json', json_encode($company_user_list, JSON_UNESCAPED_UNICODE));
        } elseif ($user_type == 2) {
            // 分公司/运营中心
            $channel_user_list = Db::name('user')->field('id,username')->where(['user_type' => 3, 'up_company_user_id' => $login_user_id])->order('id desc')->select();
            if ($channel_user_list) {
                foreach ($channel_user_list as &$v) {
                    $shop_user_list = Db::name('user')->field('id,username')->where(['user_type' => 4, 'up_channel_user_id' => $v['id']])->order('id desc')->select();
                    $v['shop_user_list'] = $shop_user_list ? : [];
                }
            }
            $this->assign('channel_user_list', $channel_user_list);
            $this->assign('channel_user_list_json', json_encode($channel_user_list, JSON_UNESCAPED_UNICODE));
        } elseif ($user_type == 3) {
            // 渠道/团队长
            $shop_user_list = Db::name('user')->field('id,username')->where(['user_type' => 4, 'up_channel_user_id' => $login_user_id])->order('id desc')->select();
            $this->assign('shop_user_list', $shop_user_list);
        } elseif ($user_type == 5) {
            // 客服
            if ($load_list) {
                $company_ids = Db::name('shop_contact')->where(['contact_id' => $login_user_id])->column('company_id');
                if ($company_ids) {
                    $company_user_list = Db::name('user')->field('id,username,mobile')->where(['user_type' => 2, 'id' => ['IN', $company_ids]])->order('id desc')->select();
                    if ($company_user_list) {
                        $channel_ids = Db::name('shop_contact')->where(['contact_id' => $login_user_id])->column('channel_id');
                        if ($channel_ids) {
                            $shop_ids = Db::name('shop_contact')->where(['contact_id' => $login_user_id])->column('shop_id');
                            foreach ($company_user_list as &$v) {
                                $channel_user_list = Db::name('user')->field('id,username')->where(['user_type' => 3, 'up_company_user_id' => $v['id'], 'id' => ['IN', $channel_ids]])->order('id desc')->select();
                                if ($channel_user_list) {
                                    if ($shop_ids) {
                                        foreach ($channel_user_list as &$val) {
                                            $shop_user_list = Db::name('user')->field('id,username')->where(['user_type' => 4, 'up_channel_user_id' => $val['id'], 'id' => ['IN', $shop_ids]])->order('id desc')->select();
                                            $val['shop_user_list'] = $shop_user_list ? : [];
                                        }
                                    } else {
                                        $val['shop_user_list'] = [];
                                    }
                                }
                                $v['channel_user_list'] = $channel_user_list ? : [];
                            }
                        } else {
                            $v['channel_user_list'] = [];
                        }
                    }
                }
            }
            $this->assign('company_user_list', $company_user_list ? : []);
            $this->assign('company_user_list_json', json_encode($company_user_list ? : [], JSON_UNESCAPED_UNICODE));
        }

        return $this->view->fetch();
    }

    public function exportClockList()
    {
        $input = Request()->param();

        $start_date = $input['start_date'] ? : '';
        $end_date = $input['end_date'] ? : '';
        $up_company_user_id = $input['company_user_id'] ? : 0;
        $up_channel_user_id = $input['channel_user_id'] ? : 0;
        $up_shop_user_id = $input['shop_user_id'] ? : 0;

        $login_user_id = session('id');
        $login_user_info = Db::name('user')->where(['id' => $login_user_id])->find();
        $user_type = $login_user_info['user_type'];

        $where_field = '';
        $user_id = $login_user_id;

        if ($user_type == 4) {
            // 门店
            $where_field = 'u.up_shop_user_id';
        } elseif ($user_type == 3) {
            // 渠道/团队长
            $where_field = 'u.up_channel_user_id';
        } elseif ($user_type == 2) {
            // 分公司/运营中心
            $where_field = 'u.up_company_user_id';
        }

        if ($up_shop_user_id) {
            $where_field = 'u.up_shop_user_id';
            $user_id = $up_shop_user_id;
        } elseif ($up_channel_user_id) {
            $where_field = 'u.up_channel_user_id';
            $user_id = $up_channel_user_id;
        } elseif ($up_company_user_id) {
            $where_field = 'u.up_company_user_id';
            $user_id = $up_company_user_id;
        }

        if ($start_date || $end_date) {
            $where['uc.ck_date'] = ['between', [$start_date, $end_date]];
            $date_desc = $start_date . '至' . $end_date;
        } else {
            $where['uc.ck_date'] = date('Y-m-d');
            $date_desc = date('Y-m-d');
        }

        $title = "{$date_desc}-财务专款计划";
        $th = ['用户名', '联系方式', '所属公司', '所属渠道', '所属门店', '所属客服', '第N天打卡', '是否超期', '是否打款', '打卡开始日期', '打卡结束日期', '预计打卡日期', '实际打卡时间', '返现小计', '打卡总计天数', '收款账户信息'];
        $td = ['username', 'mobile', 'company_name', 'channel_name', 'shop_name', 'contact_name', 'day', 'is_over', 'pay_desc', 'clock_start_date', 'clock_end_date', 'ck_date', 'ck_time', 'sum_money', 'count_success_day', 'account_info'];

        $where['uc.status'] = 2;
        if ($where_field) $where[$where_field] = $user_id;

        $load_list = true;
        if ($user_type == 5) {
            // 客服
            $user_ids = Db::name('user')->where(['contact_id' => $login_user_id])->column('id');
            if ($user_ids) {
                $where['u.id'] = ['in', $user_ids];
            } else {
                $load_list = false;
            }
        }

        if ($load_list) {
            $list = Db::name('user_clock uc')->join('ck_user u', 'uc.user_id = u.id')
                ->field('u.id,u.username,u.mobile,u.up_company_user_id,u.up_channel_user_id,u.up_shop_user_id,u.contact_id,uc.day,uc.is_over,uc.pay_status,uc.is_pay,uc.ck_date,uc.ck_time,u.account_type,u.alipay_name,u.alipay_mobile,u.bank_name,u.bank_num,u.bank_user')
                ->where($where)
                ->order('uc.ck_time asc')
                ->select();

            if ($list) {
                $data = [];
                foreach ($list as $v) {
                    $company_name = Db::name('user')->where(['id' => $v['up_company_user_id']])->value('username');
                    $channel_name = Db::name('user')->where(['id' => $v['up_channel_user_id']])->value('username');
                    $shop_name = Db::name('user')->where(['id' => $v['up_shop_user_id']])->value('username');
                    if ($contact_id = $v['contact_id']) {
                        $contact_name = Db::name('user')->where(['id' => $contact_id])->value('username');
                    } else {
                        $contact_name = '';
                    }

                    if ($v['account_type'] == 1) {
                        $account_info = "支付宝：{$v['alipay_name']} / {$v['alipay_mobile']}";
                    } else {
                        $account_info = "银行卡：{$v['bank_name']} / {$v['bank_num']} / {$v['bank_user']}";
                    }

                    $pay_desc = '';
                    if ($v['pay_status'] == 0) {
                        $pay_desc = $v['is_pay'] ? '已打款' : '未打款';
                    } else {
                        switch ($v['pay_status']) {
                            case 1:
                                $pay_desc = '待用户收款';
                                break;
                            case 2:
                                $pay_desc = '已打款';
                                break;
                            case 3:
                                $pay_desc = '未打款';
                                break;
                        }
                    }

                    // 打卡开始日期和打卡结束日期
                    $user_clock_data = Db::name('user_clock')->where(['user_id' => $v['id'], 'day' => ['IN', [1, 18]]])->order('day asc')->column('ck_date');
                    if ($user_clock_data) {
                        $clock_start_date = $user_clock_data[0] ? : '';
                        $clock_end_date = $user_clock_data[1] ? : '';
                    } else {
                        $clock_start_date = '';
                        $clock_end_date = '';
                    }

                    // 返现小计
                    $sum_money = Db::name('user_clock')->where(['user_id' => $v['id'], 'is_pay' => 1])->sum('money');

                    // 打卡总天数（复审通过）
                    $count_success_day = Db::name('user_clock')->where(['user_id' => $v['id'], 'status' => 2])->count();

                    $data[] = [
                        'username' => $v['username'],
                        'mobile' => $v['mobile'],
                        'company_name' => $company_name,
                        'channel_name' => $channel_name,
                        'shop_name' => $shop_name,
                        'contact_name' => $contact_name,
                        'day' => $v['day'],
                        'is_over' => $v['is_over'] == 1 ? '是' : '否',
                        'pay_desc' => $pay_desc,
                        'clock_start_date' => $clock_start_date,
                        'clock_end_date' => $clock_end_date,
                        'ck_date' => $v['ck_date'],
                        'ck_time' => timeFormat($v['ck_time']),
                        'sum_money' => $sum_money ? : 0,
                        'count_success_day' => $count_success_day,
                        'account_info' => $account_info
                    ];
                }
            } else {
                $data = [];
            }
        }

        exportExcel($title, $th, $td, $data);
    }

    /**
     * 通过
     * */
    public function agreeUserClockStatus()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) adminReturn(2, '请选择要审核的数据');

        $info = Db::name('user_clock')->where(['id' => $id])->find();
        if (empty($info)) adminReturn(2, '数据不存在');

        $user_info = Db::name('user')->where(['id' => $info['user_id']])->find();
        if (empty($user_info) || empty($user_info['account_type'])) {
            if (($user_info['account_type'] == 1 && (empty($user_info['alipay_name']) || empty($user_info['alipay_mobile']))) || $user_info['account_type'] == 2 && (empty($user_info['bank_name']) || empty($user_info['bank_num']) || empty($user_info['bank_user']))) {
                adminReturn(2, '用户收款信息有误');
            }
        }

        $day_money = C('DAY_MONEY');
        if ($day_money <= 0) adminReturn(2, '请先配置【每日返现金额】');

        $user_clock_data = [
            'account_type' => $user_info['account_type'],
            'alipay_name' => $user_info['alipay_name'],
            'alipay_mobile' => $user_info['alipay_mobile'],
            'bank_name' => $user_info['bank_name'],
            'bank_num' => $user_info['bank_num'],
            'bank_user' => $user_info['bank_user'],
            'money' => $day_money,
            'status' => 2,
            'remark' => '',
            'update_time' => time()
        ];
        $res = Db::name('user_clock')->where(['id' => $id])->update($user_clock_data);
        if ($res) {
            $openid = Db::name('user')->where(['id' => $info['user_id']])->value('openid');

            $data = [
                "thing1" => [
                    "value" => "第{$info['day']}天打卡天成功~点击查看您的美丽进程"
                ],
                "time2" => [
                    "value" => date('Y年m月d日 H:i')
                ]
            ];

            $id = Db::name('article')->where(['type' => 1, 'day' => $info['day']])->value('id');

            if ($openid) {
                sendWechatMsg('fubYla0hF_ah6SJOuvKfvyEY5c_i4ASAMixKllRYn84', $openid, $data, "pages/article_detail/article_detail?id={$id}");
            }

            $msg_data = insertMsgData($info['user_id'], 'clock_success', $info['day'], $id);
            Db::name('msg')->insert($msg_data);

            // 将当天被驳回的消息设置为不显示
            Db::name('msg')->where(['user_id' => $info['user_id'], 'day' => $info['day'], 'type' => 'clock_refuse', 'is_show' => 1])->setField('is_show', 0);

            if ($info['day'] == 18) {
                // 18天打卡结束
                $complete_data = [
                    "thing1" => [
                        "value" => "新用户，顺利完成18天打卡历程！"
                    ],
                    "thing3" => [
                        "value" => "恭喜完成新手任务，继续加油！"
                    ]
                ];
                $complete_ids = Db::name('article')->where(['type' => 2])->column('id');
                $complete_id = $complete_ids[rand(0, count($complete_ids) - 1)];
                if ($openid) {
                    sendWechatMsg('rIBedlMtoeEJEBQbHaDj8SID93l6X3soYULFlcdr54Y', $openid, $complete_data, "pages/article_detail/article_detail?id={$complete_id}");
                }

                $msg_data = insertMsgData($info['user_id'], 'clock_complete', $info['day'], $complete_id);
                Db::name('msg')->insert($msg_data);
            }

            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 驳回
     * */
    public function refuseUserClockStatus()
    {
        $input = Request()->param();

        $id = $input['id'];
        $remark = $input['remark'];

        if (empty($id)) adminReturn(2, '请选择要审核的数据');
        if (empty($remark)) adminReturn(2, '请填写驳回原因');

        $info = Db::name('user_clock')->where(['id' => $id])->find();
        if (empty($info)) adminReturn(2, '数据不存在');

        $res = Db::name('user_clock')->where(['id' => $id])->update(['status' => -1, 'remark' => $remark, 'update_time' => time()]);
        if ($res) {
            $msg_data = insertMsgData($info['user_id'], 'clock_refuse', $info['day']);
            Db::name('msg')->insert($msg_data);

            $openid = Db::name('user')->where(['id' => $info['user_id']])->value('openid');

            if ($openid) {
                $refuse_data = [
                    "thing1" => [
                        "value" => "第{$info['day']}天打卡被驳回"
                    ],
                    "thing4" => [
                        "value" => $remark
                    ]
                ];
                sendWechatMsg('0Yn5KHFW8ZYyi2LTEUvLHakGwSmhyX5ePqNb_ax5uCg', $openid, $refuse_data, "pages/form/form?day={$info['day']}&is_refuse=1");
            }


            if ($info['day'] == 18) {
                // 18天打卡结束
                $complete_data = [
                    "thing1" => [
                        "value" => "新用户，顺利完成18天打卡历程！"
                    ],
                    "thing3" => [
                        "value" => "恭喜完成新手任务，继续加油！"
                    ]
                ];
                $complete_ids = Db::name('article')->where(['type' => 2])->column('id');
                $complete_id = $complete_ids[rand(0, count($complete_ids) - 1)];

                if ($openid) {
                    sendWechatMsg('rIBedlMtoeEJEBQbHaDj8SID93l6X3soYULFlcdr54Y', $openid, $complete_data, "pages/article_detail/article_detail?id={$complete_id}");
                }

                $msg_data = insertMsgData($info['user_id'], 'clock_complete', $info['day'], $complete_id);
                Db::name('msg')->insert($msg_data);
            }

            adminReturn(1, '操作成功');
        } else {
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 已打款
     * */
    public function doUserClockPay()
    {
        $input = Request()->param();

        $id = $input['id'];
        $account_type = $input['account_type'];
        $img = $input['img'];


        if (empty($id)) adminReturn(2, '请选择要审核的数据');
        //        if (empty($img)) adminReturn(2, '请上传打款凭证');

        $info = Db::name('user_clock')->where(['id' => $id])->find();
        if (empty($info)) adminReturn(2, '数据不存在');

        /*$user_info = Db::name('user')->where(['id' => $info['user_id']])->find();
        if ($user_info['account_type'] == 0) {
            adminReturn(2, '操作失败，用户未完善打款信息');
        } elseif ($user_info['account_type'] == 1) {
            if (!$user_info['alipay_name'] || !$user_info['alipay_mobile']) adminReturn(2, '操作失败，用户未完善打款信息');
        } elseif ($user_info['account_type'] == 2) {
            if (!$user_info['bank_name'] || !$user_info['bank_num'] || !$user_info['bank_user']) adminReturn(2, '操作失败，用户未完善打款信息');
        }*/

        Db::startTrans();
        try {
            $clock_data = [
                'is_pay' => 1,
                'account_type' => $account_type,
                'img' => $img,
                'update_time' => time()
            ];

            /*if ($user_info['account_type'] == 1) {
                $clock_data['alipay_name'] = $user_info['alipay_name'];
                $clock_data['alipay_mobile'] = $user_info['alipay_mobile'];
            } else {
                $clock_data['bank_name'] = $user_info['bank_name'];
                $clock_data['bank_num'] = $user_info['bank_num'];
                $clock_data['bank_user'] = $user_info['bank_user'];
            }*/

            $res = Db::name('user_clock')->where(['id' => $id])->update($clock_data);
            if (!$res) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }

            switch ($account_type) {
                case 1:
                    $account_type_desc = '支付宝';
                    break;
                case 2:
                    $account_type_desc = '银行卡';
                    break;
                case 3:
                    $account_type_desc = '微信';
                    break;
            }

            $wx_data = [
                "amount9" => [
                    "value" => "￥{$info['money']}"
                ],
                "thing7" => [
                    "value" => $account_type_desc
                ],
                "thing5" => [
                    "value" => "第{$info['day']}天打卡转账"
                ]
            ];
            $openid = Db::name('user')->where(['id' => $info['user_id']])->value('openid');
            sendWechatMsg('09OC3cR_bUBqNmdbhkyKYQkdJALvmacqKZw0Z_mw6Ws', $openid, $wx_data, 'pages/voucher/voucher?day=' . $info['day']);

            $msg_data = insertMsgData($info['user_id'], 'pay_money', $info['day']);
            $res = Db::name('msg')->insert($msg_data);
            if (!$res) {
                Db::rollback();
                adminReturn(2, '操作失败');
            }

            Db::commit();
            adminReturn(1, '操作成功');
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '操作失败');
        }
    }

    /**
     * 生成打卡记录（压缩包）
     * */
    public function exportClock()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) adminReturn(2, '请选择要生成的数据');

        $info = Db::name('user_clock')->where(['id' => $id])->find();
        if (empty($info)) adminReturn(2, '数据不存在');

        $imgs_json = $info['imgs_json'] ? json_decode($info['imgs_json'], true) : [];
        $video_json = $info['video_json'] ? json_decode($info['video_json'], true) : [];
        $files = array_merge($imgs_json, $video_json);
        if (empty($files)) {
            adminReturn(2, '没有文件');
        }

        // 验证文件是否存在
        $validFiles = [];
        foreach ($files as $file) {
            $fullPath = $_SERVER['DOCUMENT_ROOT'] . str_replace(getHost(), '', $file);
            if (file_exists($fullPath)) {
                $validFiles[] = $fullPath;
            }
        }

        if (empty($validFiles)) {
            adminReturn(2, '没有有效的文件');
        }

        $user_id = $info['user_id'];
        $username = Db::name('user')->where(['id' => $info['user_id']])->value('username');

        // 创建压缩包目录
        $zipDir = $_SERVER['DOCUMENT_ROOT'] . "/clock_zip/{$user_id}";
        if (!is_dir($zipDir)) {
            if (!mkdir($zipDir, 0755, true)) {
                adminReturn(2, '创建目录失败');
            }
        }

        // 生成安全的文件名
        $safeUsername = preg_replace('/[^\w\-_\.]/', '_', $username);
        $zipFileName = "{$safeUsername}第{$info['day']}天打卡.zip";
        $save_path = "{$zipDir}/{$zipFileName}";

        // 创建压缩包
        $zipFile = createZip($validFiles, $save_path);
        if (!$zipFile || !file_exists($zipFile)) {
            adminReturn(2, '生成失败');
        }

        Db::name('user_clock')->where(['id' => $id])->update(['zip_download_url' => "/clock_zip/{$user_id}/{$zipFileName}", 'update_time' => time()]);

        adminReturn(1, '生成压缩包成功');
    }

    /**
     * 改进的文件下载方法
     */
    private function downloadZipFile($zipFilePath, $downloadFileName)
    {
        // 检查文件是否存在
        if (!file_exists($zipFilePath) || !is_readable($zipFilePath)) {
            adminReturn(2, '文件不存在或无法读取');
            return;
        }

        $fileSize = filesize($zipFilePath);
        if ($fileSize === false || $fileSize <= 0) {
            adminReturn(2, '文件大小错误');
            return;
        }

        // 清理输出缓冲区
        while (ob_get_level()) {
            ob_end_clean();
        }

        // 设置响应头
        header('Content-Description: File Transfer');
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $downloadFileName . '"');
        header('Content-Transfer-Encoding: binary');
        header('Content-Length: ' . $fileSize);
        header('Cache-Control: no-cache, no-store, must-revalidate');
        header('Pragma: no-cache');
        header('Expires: 0');

        // 防止脚本超时
        set_time_limit(300);

        // 分块读取文件以处理大文件
        $handle = fopen($zipFilePath, 'rb');
        if ($handle === false) {
            adminReturn(2, '无法打开文件');
            return;
        }

        while (!feof($handle)) {
            $buffer = fread($handle, 8192); // 8KB 缓冲区
            if ($buffer === false) {
                break;
            }
            echo $buffer;
            if (ob_get_level()) {
                ob_flush();
            }
            flush();
        }

        fclose($handle);
    }

    /**
     * 文章列表
     * */
    public function articleList()
    {
        $input = Request()->param();

        $type = $input['type'];

        $where = [];
        if ($type > 0) $where['type'] = $type;

        $page_list = Db::name('article')->where($where)->order('sort asc, id desc')->paginate()->each(function ($v) {
            $v['show_type_desc'] = $v['show_type'] == 1 ? '图文' : '视频';
            switch ($v['type']) {
                case 1:
                    $type_desc = '18天打卡内容';
                    break;
                case 2:
                    $type_desc = '18天打卡结束内容';
                    break;
                case 3:
                    $type_desc = '软文内容';
                    break;
            }
            $v['type_desc'] = $type_desc ? : '';
            return $v;
        });

        $list = Db::name('article')->where($where)->order('sort asc, id desc')->select();

        $this->assign('page_list', $page_list);
        $this->assign('list', $list);
        $this->assign('title', '文章列表');

        $count = Db::name('article')->where($where)->count();
        $this->assign('count', $count);

        $user_list = Db::name('user')->where('user_type', 1)->select();
        $this->assign('user_list', $user_list);


        return $this->view->fetch();
    }

    /**
     * 新增/编辑 文章
     * */
    public function doArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $title = $input['title'];
            $show_type = $input['show_type'] ? : 1;
            $day = $input['day'] ? : 0;
            $content = $input['content'];
            $video = $input['video'];
            $type = $input['type'] ? : 1;

            if (empty($title)) apiReturn(2, '请输入标题');
            if ($show_type == 1 && empty($content)) adminReturn(2, '请输入内容');
            if ($show_type == 2 && empty($video)) adminReturn(2, '请上传视频');
            if ($type == 1) {
                // 18天打卡内容
                if (empty($day)) adminReturn(2, '请输入天数');

                $count_where = [
                    'type' => 1,
                    'day' => $day
                ];
                if ($id) $count_where['id'] = ['neq', $id];
                $count = Db::name('article')->where($count_where)->count();
                if ($count > 0) adminReturn(2, '该天数文章已存在');
            } else {
                $day = 0;
            }

            $time = time();
            $data = [
                'title' => $title,
                'show_type' => $show_type,
                'type' => $type,
                'day' => $day
            ];
            if ($show_type == 1) $data['content'] = $content;
            if ($show_type == 2) $data['video'] = $video;

            if ($id > 0) {
                //编辑
                $data['update_time'] = $time;

                $res = Db::name('article')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('articleList'), $id > 0 ? ['reloadUrl' => true] : []);
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                //新增
                $data['create_time'] = $time;

                $res = Db::name('article')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('articleList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id > 0) {
                $info = Db::name('article')->where(['id' => $id])->find();
            }

            $this->assign('title', ($id > 0 ? '编辑' : '新增') . '文章');
            $this->assign('info', $info);

            return $this->view->fetch();
        }
    }

    /**
     * 文章排序
     * */
    public function sortArticle()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $sortObj = json_decode($input['sortObj'], true);
            $res = model('article')->saveAll($sortObj);
            if ($res) {
                adminReturn(1, '更新排序成功');
            } else {
                adminReturn(2, '更新排序失败');
            }
        }
    }

    /**
     * 软文推广
     * */
    public function confirmSpread()
    {
        $input = Request()->param();

        $id = $input['id'] ? : 0;
        $user_ids = $input['user_ids'] ? : [];

        if (empty($id)) adminReturn(2, '文章ID缺失');
        if (empty($user_ids)) adminReturn(2, '请选择用户');

        $info = Db::name('article')->where(['id' => $id])->find();
        if (empty($info)) adminReturn(2, '文章不存在或已删除');

        $list = Db::name('user')->where('user_type', 1)->whereIn('id', $user_ids)->select();
        if ($list) {
            $msg_data = [];
            foreach ($list as $v) {
                $msg_data[] = insertMsgData($v['id'], 'system_msg', 0, $id);

                // 未打卡微信通知
                $data = [
                    "thing1" => [
                        "value" => "后台系统"
                    ],
                    "thing2" => [
                        "value" => $info['title']
                    ],
                    "time3" => [
                        "value" => date('Y年m月d日')
                    ],
                    "phrase4" => [
                        "value" => '系统通知'
                    ]
                ];
                $openid = Db::name('user')->where(['id' => $v['id']])->value('openid');
                if ($openid) {
                    sendWechatMsg('txR_9lJ_rkz4GEIwbH5LGV2IbXfjsI5TzA2M4ae9pqY', $openid, $data, "pages/article_detail/article_detail?id={$id}");
                }
            }
            Db::name('msg')->insertAll($msg_data);

            adminReturn(1, '推送成功');
        }
    }

    /**
     * 删除文章
     * */
    public function delArticle()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '文章ID缺失');

        $info = Db::name('article')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('article')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 运费模板
     * */
    public function freightList()
    {
        $list = Db::name('freight')->paginate();


        $this->assign('list', $list);
        $this->assign('title', '运费模板');
        return $this->view->fetch();
    }

    /**
     * 新增/编辑 运费模板
     * */
    public function doFreight()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input['id'];
            $name = $input['name'];
            $type = $input['type'];
            $init_count = $input['init_count'];
            $init_count_price = $input['init_count_price'];
            $inc_count = $input['inc_count'];
            $inc_count_price = $input['inc_count_price'];
            $init_weight = $input['init_weight'];
            $init_weight_price = $input['init_weight_price'];
            $inc_weight = $input['inc_weight'];
            $inc_weight_price = $input['inc_weight_price'];
            $diff_freight = $input['diff_freight'];

            if (empty($name)) apiReturn(2, '请输入模板名称');

            $where['name'] = $name;
            if ($id > 0) $where['id'] = ['neq', $id];
            $count = Db::name('freight')->where($where)->count();
            if ($count > 0) adminReturn(2, '模板名称已存在');


            if (($type == 1 && (empty($init_count) || empty($init_count_price) || empty($inc_count) || empty($inc_count_price)))
                ||
                ($type == 2 && (empty($init_weight) || empty($init_weight_price) || empty($inc_weight) || empty($inc_weight_price)))
            ) adminReturn(2, '请完善计价规格');

            $time = time();
            $data = [
                'name' => $name,
                'type' => $type,
                'init_count' => $init_count,
                'init_count_price' => $init_count_price,
                'inc_count' => $inc_count,
                'inc_count_price' => $inc_count_price,
                'init_weight' => $init_weight,
                'init_weight_price' => $init_weight_price,
                'inc_weight' => $inc_weight,
                'inc_weight_price' => $inc_weight_price,
                'diff_freight' => $diff_freight,
            ];

            if ($id > 0) {
                // 编辑
                $data['update_time'] = $time;
                $res = Db::name('freight')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑成功', url('freightList'));
                } else {
                    adminReturn(2, '编辑失败');
                }
            } else {
                // 新增
                $data['create_time'] = $time;
                $res = Db::name('freight')->insert($data);
                if ($res) {
                    adminReturn(1, '新增成功', url('freightList'));
                } else {
                    adminReturn(2, '新增失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('freight')->where(['id' => $id])->find();

            $province_list = Db::name('province')->field('province_id,name province_name')->select();
            if ($province_list) {
                foreach ($province_list as &$v) {
                    $city_list = Db::name('city')->field('city_id,name city_name')->where(['province_id' => $v['province_id']])->select();
                    $v['city_list'] = $city_list;
                }
            }

            $info['diff_freight_list'] = json_decode($info['diff_freight'], true);
            $this->assign('diff_freight_data', $info['diff_freight'] ? $info['diff_freight'] : json_encode([]));
            $this->assign('info', $info);
            $this->assign('province_list', $province_list);
            $this->assign('title', ($id ? '编辑' : '新增') . '运费模板');
            return $this->view->fetch();
        }
    }

    /**
     * 服务保障
     * */
    public function serviceGuarantee()
    {
        if (Request()->isPost()) {
            $service_guarantee = Request()->param('service_guarantee');

            $res = Db::name('goods_service_guarantee')->where(' 1 = 1 ')->setField(['service_guarantee' => $service_guarantee]);
            if ($res) {
                adminReturn(1, '保存成功');
            } else {
                adminReturn(2, '保存失败');
            }
        } else {
            $service_guarantee = Db::name('goods_service_guarantee')->value('service_guarantee');

            $this->assign('service_guarantee', json_decode($service_guarantee, true));
            $this->assign('title', '服务保障');
            return $this->view->fetch();
        }
    }

    /**
     * 商品列表
     * */
    public function goodsList()
    {
        $input = Request()->param();

        $one_type_id = $input['one_type_id'];
        $two_type_id = $input['two_type_id'];

        if ($one_type_id) $where['one_type_id'] = $one_type_id;
        if ($two_type_id) $where['two_type_id'] = $two_type_id;

        $list = Db::name('goods')->where($where)->order('create_time desc')->paginate()->each(function ($item) {
            $item['one_type_name'] = Db::name('goods_type')->where(['id' => $item['one_type_id']])->value('name');
            $item['two_type_name'] = Db::name('goods_type')->where(['id' => $item['two_type_id']])->value('name');

            return $item;
        });

        $type_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => 0])->select();
        if ($type_list) {
            foreach ($type_list as &$v) {
                $son_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => $v['id']])->select();
                $v['son_list'] = $son_list;
            }
        }
        $this->assign('list', $list);

        $this->assign('type_list', $type_list);
        $this->assign('type_list_json', json_encode($type_list, JSON_UNESCAPED_UNICODE));

        $this->assign('title', '商品列表');
        return $this->fetch();
    }

    /**
     * 新增/编辑 商品
     * */
    public function doGoods()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            Db::startTrans();
            try {
                //参数处理
                parse_str($input['form'], $form);

                $price_arr = [];
                if ($form['skus']) {
                    foreach ($form['skus'] as $v) {
                        if ($v['status'] == 1) $price_arr[] = $v['price'];
                    }
                }

                $min_price = min($price_arr);
                $max_price = max($price_arr);

                $skus = $form['skus'];
                unset($form['skus']);

                $id = $form['id'];

                if (empty($form['name'])) adminReturn(2, '请输入商品名称');
                if (empty($form['img'])) adminReturn(2, '请上传封面图');
                if (empty($form['content'])) adminReturn(2, '请输入商品介绍');
                $time = time();

                $data = [
                    'name' => $form['name'],
                    'img' => $form['img'],
                    'imgs' => $form['imgs'],
                    'one_type_id' => $form['one_type_id'],
                    'two_type_id' => $form['two_type_id'],
                    'skus' => $input['skus'],
                    'min_price' => $min_price >= 0 ? $min_price : 0,
                    'max_price' => $max_price >= 0 ? $max_price : 0,
                    'product_param' => $form['product_param'] ? $form['product_param'] : '',
                    'user_instructions' => $form['user_instructions'],
                    'content' => $form['content']
                ];

                if ($id > 0) {
                    $activity_count = Db::name('activity_log')->where(['goods_id' => $id])->count();
                    if ($activity_count) adminReturn(2, '该商品活动未结束，无法编辑');

                    //编辑
                    $data['update_time'] = $time;

                    Db::name('goods')->where(['id' => $id])->update($data);

                    Db::name('sku_value')->where(['goods_id' => $id])->delete();

                    if ($skus) {
                        $sku_value = [];
                        foreach ($skus as $sku_id => &$v) {
                            $v['sku_id'] = $sku_id;
                            $v['goods_id'] = $id;

                            if ($v['picture']) {
                                $picture_info = Db::name('picture')->where(['path' => $v['picture']])->find();
                                if ($picture_info) $v['img'] = $picture_info['id'];
                            } else {
                                $v['img'] = 0;
                            }
                            unset($v['picture']);

                            $sku_value[] = $v;
                        }

                        Db::name('sku_value')->insertAll($sku_value);
                    }

                    //此行请勿删除
                    cache('sku_' . $id, null);

                    Db::commit();
                    adminReturn(1, '编辑商品成功', url('goodsList'));
                } else {
                    //新增
                    $data['create_time'] = $time;

                    $goods_id = Db::name('goods')->insertGetId($data);

                    if ($skus) {
                        $sku_value = [];
                        foreach ($skus as $sku_id => &$v) {
                            $v['sku_id'] = $sku_id;
                            $v['goods_id'] = $goods_id;

                            if ($v['picture']) {
                                $picture_info = Db::name('picture')->where(['path' => $v['picture']])->find();
                                if ($picture_info) $v['img'] = $picture_info['id'];
                            } else {
                                $v['img'] = 0;
                            }
                            unset($v['picture']);

                            $sku_value[] = $v;
                        }

                        Db::name('sku_value')->insertAll($sku_value);
                    }

                    Db::commit();
                    adminReturn(1, '新增商品成功', url('goodsList'));
                }
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试~' . $e);
            }
        } else {
            $id = Request()->param('id');

            $info = Db::name('goods')->where(['id' => $id])->find();
            $info['imgs_arr'] = doImgs($info['imgs']);
            $info['product_param'] = json_decode($info['product_param'], true);

            $type_list = Db::name('goods_type')->field('id,name')->where(['pid' => 0])->select();
            if ($type_list) {
                foreach ($type_list as &$v) {
                    $son_list = Db::name('goods_type')->field('id,name,pid')->where(['pid' => $v['id']])->select();
                    $v['son_list'] = $son_list;
                }
            } else {
                $type_list = [];
            }

            $sku_list = Db::name('sku')->field('id,name title')->where(['pid' => 0])->cache('sku')->select();
            if ($sku_list) {
                //$skus_id_arr：所有属性的id集合
                $skus_id_arr = [];

                foreach ($sku_list as &$v) {
                    if ($id > 0) {
                        $sku_value_list = Db::name('sku_value')->field('sku_id')->where(['goods_id' => $id])->select();

                        if ($sku_value_list) {
                            foreach ($sku_value_list as &$val) {
                                $sku_id = explode(' - ', $val['sku_id']);
                                if ($sku_id) {
                                    foreach ($sku_id as &$value) {
                                        if (!in_array($value, $skus_id_arr)) {
                                            $skus_id_arr[] = $value;
                                        }
                                    }
                                }
                            }
                        }

                        $parent_list = Db::name('sku')->distinct(true)->field('pid')->where(['id' => ['IN', $skus_id_arr]])->select();
                        $parent_ids = array_column($parent_list, 'pid');

                        $v['checked'] = false;
                        if (in_array($v['id'], $parent_ids)) $v['checked'] = true;
                    } else {
                        $v['checked'] = false;
                    }

                    $child = Db::name('sku')->field('id,name title')->where(['pid' => $v['id']])->select();
                    if ($child) {
                        foreach ($child as &$val) {
                            $val['checked'] = in_array($val['id'], $skus_id_arr) ? true : false;
                        }
                    }
                    $v['child'] = $child;
                }
            }

            $this->assign('title', $id ? '编辑商品' : '新增商品');

            $this->assign('info', $info);
            $this->assign('type_list', $type_list);
            $this->assign('type_list_json', json_encode($type_list, JSON_UNESCAPED_UNICODE));
            $this->assign('sku_list', json_encode($sku_list, JSON_UNESCAPED_UNICODE));
            return $this->fetch();
        }
    }

    /**
     * 删除商品
     * */
    public function delGoods()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '商品ID缺失');

        $info = Db::name('goods')->where(['id' => $id])->find();
        if ($info) {
            $activity_count = Db::name('activity_log')->where(['goods_id' => $id])->count();
            if ($activity_count) adminReturn(2, '该商品活动未结束，无法删除');

            $res = Db::name('goods')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 团购活动
     * */
    public function groupList()
    {
        $list = Db::name('group')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '团购活动');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 团购
     * */
    public function doGroup()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $goods_id = $input["goods_id"];
            $start_time = strtotime($input["start_time"]);
            $end_time = strtotime($input["end_time"]) + 24 * 3600 - 1;
            $people_number = $input["people_number"];
            $time_limit = $input["time_limit"];
            $group_price = $input["group_price"];
            $chief_price = $input["chief_price"];
            $group_limit_number = $input["group_limit_number"];

            $time = time();

            if (empty($goods_id)) apiReturn(2, '请选择商品');
            if (empty($start_time) && empty($end_time)) adminReturn(2, "请选择拼团时间");
            if ($end_time <= $time || $end_time <= $start_time) adminReturn(2, '结束拼团时间有误，请重新设置');
            if (empty($people_number)) adminReturn(2, "请输入拼团人数");
            if (empty($time_limit)) adminReturn(2, "请输入拼团时限");
            if (empty($group_price)) adminReturn(2, "请输入成团价格");
            if (empty($chief_price)) adminReturn(2, "请输入团长价格");
            if (empty($group_limit_number)) adminReturn(2, "请输入限制成团数");

            Db::startTrans();
            try {
                $goods_info = Db::name('goods')->where(['id' => $goods_id])->find();
                if (empty($goods_info)) adminReturn(2, '商品不存在或已删除');

                $data = [
                    'one_type_id' => $goods_info['one_type_id'],
                    'two_type_id' => $goods_info['two_type_id'],
                    'brand_id' => $goods_info['brand_id'],
                    'goods_name' => $goods_info['name'],
                    'goods_id' => $goods_id,
                    "start_time" => $start_time,
                    "end_time" => $end_time,
                    "people_number" => $people_number,
                    "time_limit" => $time_limit,
                    "group_price" => $group_price,
                    "chief_price" => $chief_price,
                    "group_limit_number" => $group_limit_number,
                ];

                if ($id > 0) {
                    $data['update_time'] = $time;
                    Db::name('group')->where(['id' => $id])->update($data);
                } else {
                    $data['create_time'] = $time;
                    $group_id = Db::name('group')->insertGetId($data);

                    Db::name('activity_log')->insert(['goods_id' => $goods_id, 'type' => 1]);

                    if ($group_id) {
                        $job_name = 'app\index\job\JobOrder';
                        $queue_name = "JobActivity";
                        $job_data = [
                            'obj_id' => $group_id,
                            'type' => 'group',
                        ];

                        if ($start_time > $time) {
                            // 未开始

                            // 新增开始团购活动任务
                            $job_data['node'] = 'start';
                            $start_task = Queue::later($start_time - $time, $job_name, $job_data, $queue_name);
                            if (!($start_task !== false)) {
                                Db::rollback();
                                adminReturn(2, '团购开始任务新增失败');
                            }
                        }

                        // 新增结束团购活动任务
                        $job_data['node'] = 'end';
                        $end_task = Queue::later($end_time - $time, $job_name, $job_data, $queue_name);
                        if (!($end_task !== false)) {
                            Db::rollback();
                            adminReturn(2, '团购结束任务新增失败');
                        }
                        Db::commit();
                        adminReturn(1, '提交成功', url('groupList'));
                    } else {
                        adminReturn(2, '提交失败');
                    }
                }
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('group')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '团购');

            $activity_log = Db::name('activity_log')->field('goods_id')->select();
            $activity_goods_ids = array_column($activity_log, 'goods_id');
            if ($activity_goods_ids) $where['id'] = ['NOT IN', $activity_goods_ids];

            $goods_list = Db::name('goods')->field('id,name')->where(['activity_type' => 0, 'upper' => 1])->where($where)->select();
            $this->assign('goods_list', $goods_list);

            return $this->view->fetch();
        }
    }

    /**
     * 删除团购
     * */
    public function delGroup()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '团购ID缺失');

        Db::startTrans();
        try {
            $info = Db::name('group')->where(['id' => $id])->find();

            if ($info) {
                Db::name('group')->where(['id' => $id])->delete();

                Db::name('goods')->where(['id' => $info['goods_id']])->setField('activity_type', 0);

                Db::name('activity_log')->where(['goods_id' => $info['goods_id']])->delete();

                $start_job_payload = [
                    'job' => 'app\index\job\JobOrder',
                    'data' => [
                        'obj_id' => $id,
                        'type' => 'group',
                        'node' => 'start'
                    ]
                ];
                $have_start_job = Db::name('jobs')->where(['payload' => json_encode($start_job_payload, JSON_UNESCAPED_UNICODE)])->count();
                if ($have_start_job) Db::name('jobs')->where(['payload' => json_encode($start_job_payload, JSON_UNESCAPED_UNICODE)])->delete();

                $end_job_payload = [
                    'job' => 'app\index\job\JobOrder',
                    'data' => [
                        'obj_id' => $id,
                        'type' => 'group',
                        'node' => 'end'
                    ]
                ];
                $have_end_job = Db::name('jobs')->where(['payload' => json_encode($end_job_payload, JSON_UNESCAPED_UNICODE)])->count();
                if ($have_end_job) Db::name('jobs')->where(['payload' => json_encode($end_job_payload, JSON_UNESCAPED_UNICODE)])->delete();

                Db::commit();
                adminReturn(1, '删除成功');
            } else {
                Db::rollback();
                adminReturn(2, '团购活动不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            adminReturn(2, '系统繁忙，请稍后再试');
        }
    }

    /**
     * 秒杀活动
     * */
    public function seckillList()
    {
        $list = Db::name('seckill')->paginate();

        $this->assign('list', $list);
        $this->assign('title', '秒杀活动');

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 秒杀
     * */
    public function doSeckill()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $goods_id = $input["goods_id"];
            $start_time = strtotime($input["start_time"]);
            $end_time = strtotime($input["end_time"]);
            $price = $input["price"];
            $count = $input["count"];

            $time = time();

            if (empty($goods_id)) apiReturn(2, '请选择商品');
            if (empty($start_time) && empty($end_time)) adminReturn(2, "请选择拼团时间");
            if ($end_time <= $time || $end_time <= $start_time) adminReturn(2, '结束拼团时间有误，请重新设置');
            if (empty($goods_id)) adminReturn(2, "请选择秒杀商品");
            if (empty($price)) apiReturn(2, '请输入秒杀价格');
            if (empty($count)) apiReturn(2, '请输入秒杀数量');

            Db::startTrans();
            try {
                $goods_info = Db::name('goods')->where(['id' => $goods_id])->find();
                if (empty($goods_info)) adminReturn(2, '商品不存在或已删除');

                $data = [
                    'one_type_id' => $goods_info['one_type_id'],
                    'two_type_id' => $goods_info['two_type_id'],
                    'brand_id' => $goods_info['brand_id'],
                    'goods_name' => $goods_info['name'],
                    "goods_id" => $goods_id,
                    "start_time" => $start_time,
                    "end_time" => $end_time,
                    "price" => $price,
                    "count" => $count,
                    "surplus_count" => $count
                ];

                if ($start_time >= $time) {
                    // 活动中

                    $data['status'] = 1;

                    Db::name('goods')->where(['goods_id' => $goods_id])->setField('activity_type', 2);
                } else {
                    // 未开始

                }

                if ($id > 0) {
                    $data['update_time'] = $time;
                    Db::name('seckill')->where(['id' => $id])->update($data);
                } else {
                    $data['create_time'] = $time;
                    Db::name('seckill')->insert($data);

                    Db::name('activity_log')->insert(['goods_id' => $goods_id, 'type' => 2]);
                }

                Db::commit();
                adminReturn(1, '提交成功', url('seckillList'));
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('seckill')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '秒杀');

            $activity_log = Db::name('activity_log')->field('goods_id')->select();
            $activity_goods_ids = array_column($activity_log, 'goods_id');

            if ($activity_goods_ids) $where['id'] = ['NOT IN', $activity_goods_ids];

            $goods_list = Db::name('goods')->field('id,name')->where(['activity_type' => 0, 'upper' => 1])->where($where)->select();
            $this->assign('goods_list', $goods_list);


            return $this->view->fetch();
        }
    }

    /**
     * 删除秒杀活动
     * */
    public function delSeckill()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, '秒杀活动ID缺失');

        $info = Db::name('seckill')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('seckill')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * banner列表
     */
    public function bannerList()
    {
        $list = Db::name('banner')->order('sort asc')->paginate()->each(function ($val) {
            if ($val['type'] == 1) {
                $name = Db::name('service')->where(['id' => $val['to_id']])->value('name');
                $val['obj_name'] = $name ? : '';
            } else {
                $title = Db::name('article')->where(['id' => $val['to_id']])->value('title');
                $val['obj_name'] = $title ? : '';
            }

            return $val;
        });

        $this->assign('list', $list);
        $this->assign('title', 'banner列表');

        return $this->view->fetch();
    }


    /**
     * banner排序
     * */
    public function sortBanner()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $sortObj = json_decode($input['sortObj'], true);
            $res = model('banner')->saveAll($sortObj);
            if ($res) {
                adminReturn(1, '更新排序成功');
            } else {
                adminReturn(2, '更新排序失败');
            }
        }
    }

    /**
     * 新增/编辑 banner
     * */
    public function doBanner()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $position = $input['position'] ? : 1;
            $type = $input["type"] ? : 0;
            $to_id = $input["to_id"] ? : 0;

            if (empty($img)) adminReturn(2, '请上传banner图');

            $data = [
                "img" => $img,
                "position" => $position,
                "type" => $type,
                'to_id' => $to_id
            ];

            if ($id > 0) {
                $res = Db::name('banner')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '编辑banner失败或未编辑');
                }
            } else {
                $res = Db::name('banner')->insert($data);
                if ($res) {
                    adminReturn(1, '新增banner成功', url('bannerList'));
                } else {
                    adminReturn(2, '新增banner失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('banner')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . 'banner');

            $service_list = Db::name('service_type')->field('id,name')->select();
            if ($service_list) {
                foreach ($service_list as &$v) {
                    $service = Db::name('service')->field('id,name')->where(['type_id' => $v['id']])->order('sort asc')->select();
                    $v['service'] = $service ? : [];
                }
            }
            $this->assign('service_list', $service_list);
            $this->assign('service_list_obj', json_encode($service_list, JSON_UNESCAPED_UNICODE));

            $article_list = Db::name('article')->field('id,title')->select();
            $this->assign('article_list', $article_list);

            return $this->view->fetch();
        }
    }

    /**
     * 删除banner
     * */
    public function delBanner()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'bannerID缺失');

        $info = Db::name('banner')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('banner')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }

    /**
     * 快捷入口列表
     */
    public function serviceQuickList()
    {
        $page_list = Db::name('service_quick')->order('sort asc')->paginate()->each(function ($val) {
            $name = Db::name('service')->where(['id' => $val['service_id']])->value('name');
            $val['service_name'] = $name ? : '';

            return $val;
        });

        $this->assign('page_list', $page_list);
        $this->assign('title', '快捷入口列表');

        $list = Db::name('service_quick')->order('sort asc')->select();
        $this->assign('list', $list);

        return $this->view->fetch();
    }

    /**
     * 新增/编辑 快捷入口列
     * */
    public function doServiceQuick()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $id = $input["id"];
            $img = $input["img"];
            $name = $input['name'];
            $service_id = $input["service_id"];

            if (empty($img)) adminReturn(2, '请上传封面图');
            if (empty($name)) adminReturn(2, '请输入名称');
            if (empty($service_id)) adminReturn(2, '请选择服务');

            $where['name'] = $name;
            if ($id) $where['id'] = ['neq', $id];
            $count = Db::name('service_quick')->where($where)->count();
            if ($count > 0) adminReturn(2, '该名称已存在');

            $data = [
                "img" => $img,
                "name" => $name,
                'service_id' => $service_id
            ];

            if ($id > 0) {
                $res = Db::name('service_quick')->where(['id' => $id])->update($data);
                if ($res) {
                    adminReturn(1, '编辑快捷入口成功', url('serviceQuickList'));
                } else {
                    adminReturn(2, '编辑快捷入口失败或未编辑');
                }
            } else {
                $res = Db::name('service_quick')->insert($data);
                if ($res) {
                    adminReturn(1, '新增快捷入口成功', url('serviceQuickList'));
                } else {
                    adminReturn(2, '新增快捷入口失败');
                }
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('service_quick')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '编辑' : '新增') . '快捷入口');

            $service_list = Db::name('service_type')->field('id,name')->select();
            if ($service_list) {
                foreach ($service_list as &$v) {
                    $service = Db::name('service')->field('id,name')->where(['type_id' => $v['id']])->order('sort asc')->select();
                    $v['service'] = $service ? : [];
                }
            }
            $this->assign('service_list', $service_list);
            $this->assign('service_list_obj', json_encode($service_list, JSON_UNESCAPED_UNICODE));

            $list = Db::name('service_quick')->order('sort asc')->select();
            $this->assign('list', $list);

            return $this->view->fetch();
        }
    }

    /**
     * 快捷入口排序
     * */
    public function sortServiceQuick()
    {
        if (Request()->isPost()) {
            $input = Request()->param();

            $sortObj = json_decode($input['sortObj'], true);
            $res = model('service_quick')->saveAll($sortObj);
            if ($res) {
                adminReturn(1, '更新排序成功');
            } else {
                adminReturn(2, '更新排序失败');
            }
        }
    }

    /**
     * 删除快捷入口
     * */
    public function delServiceQuick()
    {
        $id = Request()->param('id');

        if (empty($id)) adminReturn(2, 'ID缺失');

        $info = Db::name('service_quick')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('service_quick')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除成功');
            } else {
                adminReturn(2, '删除失败');
            }
        } else {
            adminReturn(2, '数据不存在或已删除');
        }
    }


    /**
     * 评分列表
     * */
    public function scoreList()
    {
        $input = Request()->param();

        $type = $input['type'] ? : '';
        $user_id = $input['user_id'] ? : 0;

        if ($type) $where['l.type'] = $type;
        if ($user_id) $where['l.user_id'] = $user_id;

        $list = Db::name('user_score_log l')->join('user u', 'l.user_id = u.id', 'left')
            ->field('l.*,u.username,u.mobile')
            ->order('l.id desc')
            ->where($where)
            ->paginate()->each(function ($val) {
                if ($val['type'] == 'comment') $service_name = Db::name('order')->where(['id' => $val['link_id']])->value('service_name');
                $val['service_name'] = $service_name ? : '';

                return $val;
            });
        $this->assign('list', $list);

        $this->assign('title', '评分列表');

        return $this->view->fetch();
    }

    /**
     * 订单列表
     */
    public function orderList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $channel_user_id = $input['channel_user_id'];
        $service_name = $input['service_name'];
        $status = $input['status'];
        $date_range = $input['date_range'] ? : '';

        if (!empty($user_id)) $where["user_id"] = $user_id;
        if (!empty($channel_user_id)) $where["channel_user_id"] = $channel_user_id;
        if (!empty($service_name)) $where["service_name"] = ['LIKE', "%$service_name%"];
        if (!empty($status)) $where["status"] = $status;
        if ($date_range) {
            $date = explode(' - ', $date_range);
            $start_time = strtotime($date[0]);
            $end_time = strtotime($date[1]);

            $where["create_time"] = ['between', [$start_time, $end_time + 60 * 60 * 24 - 1]];
        }

        $list = Db::name('order')->where($where)->order('id desc')->paginate()->each(function ($val) {
            $supplier_user_info = Db::name('user_ident')->where(['user_id' => $val['user_id'], 'type' => 1])->find();
            $val['supplier_username'] = $supplier_user_info['username'] ? : '';
            $val['supplier_mobile'] = $supplier_user_info['mobile'] ? : '';

            $channel_user_info = Db::name('user_ident')->where(['user_id' => $val['channel_user_id'], 'type' => 2])->find();
            $val['channel_username'] = $channel_user_info['username'] ? : '';
            $val['channel_mobile'] = $channel_user_info['mobile'] ? : '';

            return $val;
        });

        $this->assign('list', $list);
        $this->assign('title', '订单列表');

        $supplier_user_list = Db::name('user_ident')->field('id,user_id,username,mobile')->where(['type' => 1, 'status' => 1])->select();
        $this->assign('supplier_user_list', $supplier_user_list);
        $channel_user_list = Db::name('user_ident')->field('id,user_id,username,mobile')->where(['type' => 2, 'status' => 1])->select();
        $this->assign('channel_user_list', $channel_user_list);

        return $this->fetch();
    }

    /**
     * 派单 / 重新派单
     * */
    public function editChannel()
    {
        $input = Request()->param();

        $id = $input['id'];
        $channel_user_id = $input['channel_user_id'];

        if (empty($id)) adminReturn(2, 'ID缺失');
        if (empty($channel_user_id)) adminReturn(2, '请选择渠道商');

        $order_info = Db::name('order')->where(['id' => $id])->find();
        if (empty($order_info)) adminReturn(2, '订单不存在或已删除');

        if ($order_info['status'] == 3) adminReturn(2, '该订单已完成，无法派单');

        if ($order_info['user_id'] == $channel_user_id) adminReturn(2, '供应商和渠道商是同一账号，无法派单');

        $data = [
            'update_time' => time(),
            'channel_user_id' => $channel_user_id,
            'status' => 2
        ];
        $res = Db::name('order')->where(['id' => $id])->update($data);
        if ($res) {
            adminReturn(1, '派单成功', url('orderList'));
        } else {
            adminReturn(2, '派单失败或未修改派单人');
        }
    }

    /**
     * 订单详情
     */
    public function doOrder()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input["id"];

            $order_info = Db::name("order")->where(["id" => $id])->find();
            if ($order_info['status'] == 2) {
                $status = 3;
                $express_id = $input["express_id"];
                $send_num = $input["send_num"];
                if (empty($send_num)) adminReturn(2, "请输入快递编号");
                Db::startTrans();
                $data = [
                    "status" => $status,
                    "express_id" => $express_id,
                    "send_num" => $send_num,
                ];

                $data['update_time'] = time();
                $res = Db::name('order')->where(['id' => $id])->update($data);
                if ($res) {
                    /** 添加发送消息 */
                    $data_msg = [
                        "user_id" => $order_info["user_id"],
                        "order_id" => $id,
                        "title" => "您的订单已经发货",
                        "content" => "您的订单已经发货",
                        "type" => 1,
                        "create_time" => time(),
                    ];
                    Db::name("msg")->insert($data_msg);

                    /** 添加15天自动确认收货计划 */
                    $time = time() + 24 * 3600 * C('CONFIRM_GET_DAY');
                    $data_plan = [
                        "user_id" => $order_info["user_id"],
                        "order_id" => $id,
                        "type" => 2,
                        "execute_date" => date('Y - m - d', $time),
                    ];
                    Db::name("plan")->insert($data_plan);

                    Db::commit();
                    adminReturn(1, '编辑成功', url('orderList'));
                } else {
                    Db::rollback();
                    adminReturn(2, '系统繁忙，请稍后再试');
                }
            } elseif ($order_info['status'] == 7) {
                $after_status = $input['after_status'];
                $after_refuse_reason = $input['after_refuse_reason'];
                if (empty($after_status)) adminReturn(2, '请选择售后操作');
                if ($after_status == 3 && empty($after_refuse_reason)) adminReturn(2, "请输入拒绝原因");

                $time = time();

                Db::startTrans();
                try {
                    $data = [
                        'back_order_sn' => $order_info['pay_order_sn'],
                        'status' => 8,//订单状态改成售后完成
                        'after_status' => $after_status,
                        'after_refuse_reason' => $after_refuse_reason,
                        'update_time' => $time
                    ];
                    Db::name('order')->where(['id' => $id])->update($data);

                    $price = $order_info['pay_price'];
                    /**
                     * @TODO 第5点暂时不做处理
                     * 同意售后【退货退款】（对应支付成功做退回处理）
                     * 1：金额原路退回（微信退款 || 收益退款）  注：如果是收益退款的话需要生成对应的收益记录，且用户可用收益增加
                     * 3：减少商品销量
                     * 4：增加商品库存
                     * 5：用户is_activation修改为已激活状态（1）【暂时不做处理】
                     * 6：冻结的直推、级差、服务津贴作废（作废）
                     * 7：删除自动确认收货任务
                     * 同意售后【换货】
                     * 1：订单变成待收货状态
                     * 2：删除原来的自动确认收货任务
                     * 3：新增自动确认收货任务
                     * */
                    if ($after_status == 2) {
                        // 同意售后

                        if ($input['after_type'] == '退货退款') {
                            $vice_order_info = Db::name('vice_order')->where(['order_id' => $id])->find();

                            // 1：金额原路退回
                            if ($order_info['pay_type'] == 1) {
                                //微信支付
                                Loader::import('wxpaysdk\wxPay', EXTEND_PATH);
                                $obj = new \wxPay();

                                $obj->refund($price, $price, $order_info['pay_order_sn'], $order_info['pay_order_sn'], $order_info['after_reason']);
                            } else {
                                $user_id = $order_info['user_id'];

                                $user_info = Db::name('user')->where(['id' => $user_id])->find();
                                $mobile = $user_info['mobile'] ? : '';
                                $gzh_openid = $user_info['gzh_openid'];

                                Db::name('user')->where(['id' => $user_id])->setInc('all_profit', $price);

                                //收益支付
                                $profit_data = [
                                    'order_id' => $id,
                                    'user_id' => $order_info['user_id'],
                                    'price' => $order_info['pay_price'],
                                    'type' => 12,
                                    'status' => 2,
                                    'create_time' => $time
                                ];
                                Db::name('profit')->insert($profit_data);

                                // 发送微信公众号模板消息
                                $template_msg = [
                                    'first' => [
                                        'value' => '您好，您的售后订单购物抵扣收益已退回',
                                        'color' => '#743A3A'
                                    ],
                                    'keyword1' => [
                                        'value' => '购物抵扣收益退款',
                                        'color' => '#743A3A'
                                    ],
                                    'keyword2' => [
                                        'value' => $price,
                                        'color' => '#743A3A'
                                    ],
                                    'keyword3' => [
                                        'value' => date('Y-m-d'),
                                        'color' => '#743A3A'
                                    ],
                                    'keyword4' => [
                                        'value' => '点击查看',
                                        'color' => '#743A3A'
                                    ],
                                    'remark' => [
                                        'value' => '',
                                        'color' => '#743A3A'
                                    ]
                                ];
                                $page = 'pages/my_income/my_income?user_id=' . $user_id . '&mobile=' . $mobile;
                                if ($gzh_openid && $price > 0) sendWxTemplateNotice($gzh_openid, $template_msg, 12, $page);
                            }

                            $buy_count = $vice_order_info['count'];
                            $goods_id = $vice_order_info['goods_id'];
                            $sku_id = $vice_order_info['sku_id'];

                            // 3：减少商品销量
                            $goods_info = Db::name('goods')->where(['id' => $goods_id])->find();
                            if ($goods_info && $buy_count > 0) Db::name('goods')->where(['id' => $goods_id])->setDec('sales_count', $buy_count);

                            // 4：增加商品库存
                            $sku_info = Db::name('sku_value')->where(['goods_id' => $goods_id, 'sku_id' => $sku_id])->find();
                            if ($sku_info && $buy_count > 0) Db::name('sku_value')->where(['goods_id' => $goods_id, 'sku_id' => $sku_id])->setInc('stock', $buy_count);

                            // 6：冻结的直推、级差、服务津贴作废（作废）
                            $frozen_profit_list = Db::name('profit')->where(['order_id' => $id, 'type' => ['IN', [1, 2, 3]]])->select();
                            if ($frozen_profit_list) {
                                $update_profit_data = ['status' => -1,
                                                       'update_time' => $time];
                                Db::name('profit')->where(['order_id' => $id, 'type' => ['IN', [1, 2, 3]]])->update($update_profit_data);
                            }

                            // 7：删除自动确认收货任务
                            Db::name('plan')->where(['order_id' => $id, 'type' => 2])->delete();
                        } else
                            if ($input['after_type'] == '换货') {
                                // 1：订单变成待收货状态
                                $change_order_data = [
                                    'status' => 3,
                                    'update_time' => $time
                                ];
                                Db::name('order')->where(['id' => $id])->update($change_order_data);
                                // 2：删除原来的自动确认收货任务
                                Db::name('plan')->where(['order_id' => $id, 'type' => 2])->delete();
                                // 3：新增自动确认收货任务
                                $time = time() + 24 * 3600 * C('CONFIRM_GET_DAY');
                                $data_plan = [
                                    "user_id" => $order_info["user_id"],
                                    "order_id" => $id,
                                    "type" => 2,
                                    "execute_date" => date('Y-m-d', $time),
                                ];
                                Db::name("plan")->insert($data_plan);
                            }
                    }

                    Db::commit();
                    adminReturn(1, '操作成功', url('orderList'));
                } catch
                (\Exception $e) {
                    Db::rollback();
                    adminReturn(2, '系统繁忙，请稍后再试~');
                }
            }
        } else {
            $id = input("id");
            $order_info = Db::name('order a')->field("a.*,b.mobile,b.username")->where(["a.id" => $id])->join('user b', "a.user_id = b.id", "left")->find();
            $order_vice = Db::name("vice_order")->where(["order_id" => $id])->select();
            foreach ($order_vice as &$vo) {
                $suk_value_arr = explode("-", $vo['sku_id']);
                $suk_name_str = "";
                foreach ($suk_value_arr as $vv) {
                    $sku_info = Db::name("sku")->where(["id" => $vv])->find();
                    $sku_p_info = Db::name("sku")->where(["id" => $sku_info['pid']])->find();
                    $suk_name_str .= $sku_p_info['name'] . ": " . $sku_info['name'] . ";";
                }
                $vo['suk_name_str'] = $suk_name_str;
                $gift_ids_arr = explode("-", $vo['gift_ids']);

                /** 查看商品是不是有评论 */
                $is_have = Db::name('goods_comment')->where(["order_id" => $id, "goods_id" => $vv['goods_id']])->value("id");
                if ($is_have) {
                    $is_comment = $is_have;
                } else {
                    $is_comment = 0;
                }
                $vo['is_comment'] = $is_comment;
            }

            //查询出快递公司
            $express_list = Db::name("express")->field("id,name")->select();

            if ($express_id = $order_info['express_id']) $order_info['express_name'] = Db::name('express')->where(['id' => $express_id])->value('name');

            $this->assign('info', $order_info);
            $this->assign('order_vice', $order_vice);
            $this->assign('express_list', $express_list);

            $this->assign('title', '订单详情');
            return $this->fetch();
        }
    }

    /**
     *商品评论
     */
    public function doComment()
    {
        $input = Request()->param();
        $id = $input["id"];

        //查询出评论内容
        $info = Db::name('goods_comment')->where(["id" => $id])->find();

        $info["img_arr"] = explode(",", $info["imgs"]);

        $this->assign('info', $info);
        $this->assign('title', '评论详情');
        return $this->fetch();
    }

    /**
     * 公告列表
     */
    public function msgList()
    {
        $input = Request()->param();

        $title = $input['title'];
        $where["type"] = 3;
        if ($title) $where['title'] = ["like", '%' . $title . '%'];
        $list = Db::name('msg')->where($where)->order('create_time desc')->paginate();


        $this->assign('list', $list);

        $this->assign('title', '公告列表');

        return $this->fetch();
    }

    /**
     * 新增/编辑 公告
     */
    public function doMsg()
    {
        if (Request()->isPost()) {
            $input = Request()->param();
            $id = $input['id'];
            $title = $input["title"];
            $content = $input["content"];

            if (empty($title)) adminReturn(2, "请输入标题");
            if (empty($content)) adminReturn(2, "请填写公告内容");

            if ($id) {
                $data = [
                    'title' => $title,
                    'content' => $content
                ];

                $res = Db::name('msg')->where(['id' => $id])->update($data);
            } else {
                $data = [
                    "user_id" => 0,
                    "title" => $title,
                    "content" => $content,
                    "type" => 3,
                    "look_count" => 0,
                    "create_time" => time()
                ];

                $res = Db::name('msg')->insert($data);
            }

            if ($res) {
                adminReturn(1, ($id ? '编辑' : '新增') . '公告成功', url('msgList'));
            } else {
                adminReturn(2, ($id ? '编辑' : '新增') . '公告失败');
            }
        } else {
            $id = Request()->param('id');

            if ($id) $info = Db::name('msg')->where(['id' => $id])->find();

            $this->assign('info', $info);
            $this->assign('title', ($id ? '公告详情' : '新增公告'));

            return $this->view->fetch();
        }
    }

    /**
     * 删除公告
     */
    public function delMsg()
    {
        $input = Request()->param();

        $id = $input["id"];

        if ($id > 0) {
            $res = Db::name('msg')->where(['id' => $id])->delete();
            if ($res) {
                adminReturn(1, '删除公告成功', url('msgList'));
            } else {
                adminReturn(2, '删除公告失败');
            }
        }
    }

    /**
     * 微信打卡返现
     * */
    public function mchMoney()
    {
        $input = Request()->param();

        $id = $input['id'];

        $info = Db::name('user_clock')->where(['id' => $id])->find();
        if (empty($info)) adminReturn(2, '打卡记录不存在');

        $user_id = $info['user_id'];
        if (empty($user_id)) adminReturn(2, '用户ID缺失');

        $openid = Db::name('user')->where(['id' => $user_id])->value('openid');
        if (empty($openid)) adminReturn(2, 'OPENID不存在');

        $money = $info['money'];
        if ($money < 0.1 || $money > 200) adminReturn(2, '返现金额错误');

        $obj = new Transfer();
        $res = $obj->send($openid, $money * 100);
        if ($res !== false) {
            $data = [
                'order_sn' => $res['out_bill_no'],
                'package_info' => $res['package_info'],
                'transfer_bill_no' => $res['transfer_bill_no'],
                'pay_status' => 1,
                'update_time' => time()
            ];
            $result = Db::name('user_clock')->where(['id' => $id])->update($data);
            if ($result) {
                if ($res['package_info']) {
                    $wx_data = [
                        "amount9" => [
                            "value" => "￥{$money}"
                        ],
                        "thing7" => [
                            "value" => '微信'
                        ],
                        "thing5" => [
                            "value" => "第{$info['day']}天打卡金已转，请点击确认收款"
                        ]
                    ];
                    sendWechatMsg('09OC3cR_bUBqNmdbhkyKYQkdJALvmacqKZw0Z_mw6Ws', $openid, $wx_data, 'pages/index/index?package_info=' . $info['package_info'] . '&mch_id=' . C('MCH_ID'));
                }

                $msg_data = insertMsgData($user_id, 'transfer_pay_money', $info['day']);
                $res = Db::name('msg')->insert($msg_data);
                if (!$res) {
                    adminReturn(2, '操作失败');
                }

                adminReturn(1, '操作成功');
            } else {
                adminReturn(2, '操作失败');
            }
        } else {
            adminReturn(2, '操作失败');
        }

    }

    /**
     * 打卡虚拟数据
     * */
    public function clockVirtual()
    {
        if (Request()->isPost()) {
            $user_virtual_data = Request()->param('user_virtual_data');
            $background_virtual_data = Request()->param('background_virtual_data');
            $is_open = Request()->param('is_open');

            Db::startTrans();
            try {
                $user_virtual_data_arr = explode(',', $user_virtual_data);
                if (count($user_virtual_data_arr) < 3) adminReturn(2, '最少3个内容');

                $background_virtual_data_arr = explode(',', $background_virtual_data);
                if (count($background_virtual_data_arr) < 3) adminReturn(2, '最少3个颜色');

                $res = Db::name('virtual')->where('id', 1)->update(['data' => json_encode($user_virtual_data_arr, JSON_UNESCAPED_UNICODE), 'update_time' => time()]);
                if (!$res) throw new \Exception();

                $res = Db::name('virtual')->where('id', 2)->update(['data' => $background_virtual_data, 'update_time' => time()]);
                if (!$res) throw new \Exception();

                $res = Db::name('virtual')->where('id', 3)->update(['data' => $is_open, 'update_time' => time()]);
                if (!$res) throw new \Exception();

                Db::commit();
                adminReturn(1, '操作成功');
            } catch (\Exception $e) {
                Db::rollback();
                adminReturn(2, '操作失败' . $e->getMessage());
            }
        } else {
            $user_virtual_data = Db::name('virtual')->where('id', 1)->value('data');

            $background_virtual_data = Db::name('virtual')->where('id', 2)->value('data');
            $background_virtual_data = explode(',', $background_virtual_data);
            $is_open = Db::name('virtual')->where('id', 3)->value('data');

            $this->assign('user_virtual_data', json_decode($user_virtual_data, true));
            $this->assign('background_virtual_data', $background_virtual_data);
            $this->assign('is_open', $is_open);

            $this->assign('title', '打卡虚拟数据');
            return $this->view->fetch();
        }
    }

}
